我想通过列表(用户输入的范围)迭代,首先假定所有数字都是素数(P),并让程序遍历列表。当列表中的元素为P时,我想遍历范围内的所有倍数并将它们改为N.当元素为N时,我希望程序移动到下一个数字(我将0和1设置为不是素数因为它们是例外)。我遇到索引问题,但是,我得到的错误:通过迭代(python)更改列表元素
list1[number1] = 'N'
IndexError: list assignment index out of range
当我运行我有的程序。这里是代码:
# input
n = int(input("Enter a positive integer greater than or equal to 10: "))
while n < 10:
print ("Invalid! Try again")
int(input("Enter a positive integer greater than or equal to 10: "))
# create list
new_n = n + 1
list1 = ['P'] * new_n
# set non prime
list1[0] = 'N'
list1[1] = 'N'
# set up loop
counter = 0
for x in list1:
counter1 = 2
if list1[counter] == 'P':
for y in list1:
number1 = counter * counter1
list1[number1] = 'N'
counter1 += 1
counter += 1
else:
counter += 1
任何帮助,将不胜感激!谢谢。
提示:使用'枚举()',而不是一个原始指数环。它会让您同时访问元素及其相应的索引。 –
@AkshatMahajan谢谢!我现在正在这样做。但是,如果我列举了列表,我怎么能索引与列表中的元素相对应的数字。例如,在像(2,P)这样的枚举列表中,我如何将2作为int来索引? –
你想要做'对于索引,枚举(list1)'中的项来访问'item'的相应索引。 –