2017-12-02 81 views
0

我想讀的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

回答

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中。

+0

一個小的補充:如果將int()添加到列表創建中,則不必再處理字符串,並可以用循環引用x來替換循環中的所有'num'。這是假設你的文件只包含整數。 (int(numbers.readline()。rstrip('\ n'))))'nums.append – ikom

相關問題