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

试图从列表打印数量,类型错误:列表索引必须是整数,而不是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

+0

您的'for'循环遍历'nums'的成员,所以'x'不是一个整数。你只需要'num = int(x)'。 – excaza

+0

错误清楚地提到列表中的值是文本,而不是整数。因此,首先必须将其转换为整数,然后对其执行操作。 – Sam

你已经在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中。

+0

一个小的补充:如果将int()添加到列表创建中,则不必再处理字符串,并可以用循环引用x来替换循环中的所有'num'。这是假设你的文件只包含整数。 (int(numbers.readline()。rstrip('\ n'))))'nums.append – ikom