试图从列表打印数量,类型错误:列表索引必须是整数,而不是str的

我想读的7试图从列表打印数量,类型错误:列表索引必须是整数,而不是str的

numbers = open('numbers' , 'r') 

nums=[]

cnt=1

while cnt<20:

nums.append(numbers.readline().rstrip('\n'))

cnt += 1

print nums

oddNumbers = []

multiplesOf7 = []

for x in nums:

num = int(nums[x])

if num%2 > 0 :

oddNumbers.append(num)

elif num%7 > 0 :

multiplesOf7.append(num)

print('Odd numbers: ' , oddNumbers)

print('Multiples of 7: ' , multiplesOf7)

从文本文件号码(20号)和打印奇数和倍数我越来越

Traceback (most recent call last): ['21', '26', '27', '28', '7', '14', '36', '90', '85', '40', '60', '50', '55', '45', '78', '24', '63', '75', '12'] File "C:/Users/y0us3f/PycharmProjects/Slimanov/oddmultiples.py", line 16, in num = int(nums[x]) TypeError: list indices must be integers, not str

Process finished with exit code 1

回答:

你已经在nums内迭代值。不要再抬头从NUMS值:

# nums = ['21', '26', '27', '28', '7', '14', '36', '90', '85', '40', '60', '50', '55', '45', '78', '24', '63', '75', '12'] 

for x in nums:

# x is '21', '26', etc.

num = int(x)

...

你得到一个例外,因为你想查找使用字符串指数NUMS值:nums['21'],但在这种情况下,你不”您甚至需要,因为您已经将值'21'存储在x中。

以上是 试图从列表打印数量,类型错误:列表索引必须是整数,而不是str的 的全部内容, 来源链接: utcz.com/qa/258245.html

回到顶部