【问题标题】:Beginner Python question: trouble converting list objects to integers初学者 Python 问题:将列表对象转换为整数时遇到问题
【发布时间】:2020-07-31 16:14:33
【问题描述】:

这段代码导致了

TypeError: 'list' object cannot be interpreted as an integer.

在添加用户输入之前它正在工作。该代码返回数字与输入数字对的范围重叠的次数。提前致谢!

user_input_1 = input("Enter the first pair here: ")
lst1 = [int(i) for i in user_input_1.split(" ") if i.isdigit()]

user_input_2 = input("Enter the second pair here: ")
lst2 = [int(i) for i in user_input_2.split(" ") if i.isdigit()]

user_input_3 = input("Enter the third pair here: ")
lst3 = [int(i) for i in user_input_3.split(" ") if i.isdigit()]

user_input_4 = input("Choose a center number: ")
number = int(user_input_4)


mainlist = [[lst2], [lst2], [lst3]]

def count_overlapping(mainlist, number): 
    count = 0
    for element in mainlist:
        if number in range(element[0], element[-1]) or number == element[0] or number == element[-1]:
            count += 1
    return count    

print(count_overlapping(mainlist, number))

【问题讨论】:

  • 你应该打印mainlist 看看它是否真的是你想要的。看起来您多了一层嵌套。
  • 正如 Mark Meyer 所说,您的主列表有一个额外的级别,将其更改为 mainlist = [lst2, lst2, lst3] 应该可以工作。
  • 啊!谢谢,就是这样

标签: python list integer typeerror


【解决方案1】:

你有一个额外级别的列表,你不需要,所以当你认为你得到一个 int 值时,你仍然得到一个列表。

mainlist = [[lst2], [lst2], [lst3]] 更改为mainlist = [lst2, lst2, lst3]

mainlst = [[lst1], [lst2], [lst3]]
[[[1, 2, 3, 4, 5, 6, 7, 8, 9]],
 [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]],
 [[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]]

mainlst = [lst1, lst2, lst3]                                                                                     
[[1, 2, 3, 4, 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]]

【讨论】:

    【解决方案2】:

    mainlist 是一个列表列表,你应该使用:

    mainlist = [lst2, lst2, lst3]
    

    另外,您可以改进您的功能count_overlapping(假设您的输入有成对的数字/2 个数字):

    def count_overlapping(mainlist, number):
        return sum(1 for [a, b] in mainlist if number >= a and number <= b)
    

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 2019-11-03
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多