【问题标题】:python: in put lists from keyboardpython:从键盘输入列表
【发布时间】:2017-06-11 03:24:44
【问题描述】:

编写python程序合并两个排序列表,尝试从键盘输入这两个列表的值,但是在开始运行时尝试输入第一个值,它会出错:

输入list1:1的整数

回溯(最近一次通话最后一次):
文件“C:/Python/PythonProject/mergeTwoLists_leetcode.py”,第 20 行,<module>

list1[i] = input("请输入list1的整数:")

IndexError:列表分配索引超出范围

程序是:

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]

标签: python


【解决方案1】:

您将 list1 初始化为一个空列表

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 中不存在的索引,因为空列表的长度为零。

(仅供参考,此答案特定于您的错误,而不是您的代码的其余部分)

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

【讨论】:

    【解决方案2】:
    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()
    

    这是错误的,因为 list1 是一个空列表,所以您的位置不存在

    【讨论】:

      【解决方案3】:

      使用eval函数将帮助您输入一个列表

      listos = eval(input('enter a comma seperated list))
      listos.split()
      

      split()用于sep列表用逗号括起来。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-13
        相关资源
        最近更新 更多