我想讀的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
您的'for'循環遍歷'nums'的成員,所以'x'不是一個整數。你只需要'num = int(x)'。 – excaza
錯誤清楚地提到列表中的值是文本,而不是整數。因此,首先必須將其轉換爲整數,然後對其執行操作。 – Sam