編寫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)
你能幫助我爲
FWIW,除非你有一些複雜的組合邏輯,合併列表一樣簡單:'[ 1,2,3] + [4,5,6]',這將產生'[1,2,3,4,5,6]'。 – blacksite