2017-01-25 62 views
1

編寫Python程序,以合併兩個排序列表,嘗試輸入從鍵盤這兩個列表的值,但開始運行時,嘗試輸入第一個值,它的錯誤:蟒蛇:從鍵盤放列表

enter a integer of list1:1

Traceback (most recent call last):
   File "C:/Python/PythonProject/mergeTwoLists_leetcode.py", line 20, in <module>

list1[i] = input("enter a integer of list1:")

IndexError: list assignment index out of range

的程序是:

class ListNode(object): 
    def __init__(self,x): 
     self.val = x 
     elf.next = None 

class MergeTwoLists(object): 
    def mergeTwoLists(self,l1,l2): 
     if not li or not l2: 
      return l1 or l2 
     if l1.val < l2.val: 
      l1.next = mergeTwoLists(l1.next,l2) 
      return l1 
     else: 
      l2.next = mergeTwoLists(l1,l2.next) 
      return l2 

#input the two integer lists 
list1 = [] 
for i in range(0,6): 
    list1[i] = input("enter a integer of list1:") 
head = ListNode(list1[0]) 
p = head 
for j in list1[1:]: 
    node = ListNode(j) 
    p.next = node 
    p = p.next 
l1 = head 

list2 = [] 
for i in range(0,6): 
    list2[i] = input("enter an integer of list2:") 
head = ListNode(list2[0]) 
p = head 
for j in list2[1:]: 
    node = ListNode(j) 
    p.next = node 
    p = p.next 
l2 = head 

list_result = MergeTwoLists().mergeTwoLists(l1,l2) 
print("the list result:") 
print(list_result) 

你能幫助我爲

+0

FWIW,除非你有一些複雜的組合邏輯,合併列表一樣簡單:'[ 1,2,3] + [4,5,6]',這將產生'[1,2,3,4,5,6]'。 – blacksite

回答

0
list1 = [] 
list2 = [] 
for i in range(0,6): 
    list1.append(input("enter a integer of list1:")) 
for i in range(0,6): 
    list2.append(input("enter an integer of list2:")) 

total_list = list1 + list2 
total_list.sort() 

它的示數是原因列表1是一個空的列表,以便您的位置是不存在的

1

您初始化列表1空列表

list1 = [] 

爲了一個新的項目添加到列表中使用的append()結束

for i in range(0,6): 
    list1.append(input("enter a integer of list1:")) 

在您的例子

for i in range(0,6): 
    list1[i] = input("enter a integer of list1:") 

你都拿到一個IndexError因爲你試圖訪問list1中不存在的索引,因爲空列表的長度爲零。

(FYI這個答案是具體到你的錯誤,不是你的代碼的其餘部分)

文檔:https://docs.python.org/3/tutorial/datastructures.html