Python初学者在这里.为什么以下代码会导致TypeError



有人知道为什么这会导致TypeError:int((参数必须是字符串、类似字节的对象或数字,而不是"list"吗?

user_input = input("Please enter a list of numbers here: ")
lst4 = user_input.split()
def sum67(lst4):
segment_one = []
segment_two = []
for i in range(len(lst4)):
if int(lst4[i]) == 6:
segment_one.append(int(lst4[0:i]))
for i2 in range(len(lst4)):
if int(lst4[i2]) == 7 and i2 > len(segment_one):
segment_two.append (int(lst4[i2+1:])) 
complete_list = segment_one + segment_two
total = 0 
for groups in complete_list:
for value in groups:
total += value
return total   
print(sum67(lst4))

以下是完整的输入和错误消息:

Please enter a list of numbers here: 2 3 4 6 7 8
Traceback (most recent call last):
File "/Users/lucasjacaruso/Desktop/Calc Course/Powers_list.py", line 21, in <module>
print(sum67(lst4))    
File "/Users/lucasjacaruso/Desktop/Calc Course/Powers_list.py", line 9, in sum67
segment_one.append(int(lst4[0:i]))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

这一切都是因为你的代码的这一部分:

segment_one.append(int(lst4[0:i]))

segment_two.append (int(lst4[i2+1:])) 

lst4[0:i]返回list,但int((参数必须是字符串、类似字节的对象或错误消息中所说的数字。与lst4[i2+1:]相同。

例如,如果您的输入是"10 11 6 12",那么lst4[0:i]将返回[10,11]。如果你试着打电话:

int([10, 11])

您将收到相同的错误消息。

您的代码不考虑格式错误的输入,如字母数字输入和多个空格。您的第二行可以如下所示。此外,您以后不必进行int转换,因为您的lst4默认情况下是一个int列表

lst4 = [int(i) for i in user_input.split(" ") if i.isdigit()]

相关内容

最新更新