我试图遍历一个列表(用户输入的范围),首先假设所有数字都是质数(P),然后让程序遍历该列表。当列表中的元素为P时,我要遍历范围内的所有倍数并将其更改为N。当元素为N时,我希望程序移至下一个数字(我将0和1设置为不作质数,因为它们是例外)。我遇到索引问题,但是出现错误:

 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


任何帮助,将不胜感激!谢谢。

最佳答案

在循环中,您仅将平方值设置为非质数,因为您在counter的循环中迭代counter1

然后,您必须检查number1是否小于list1的大小。

您还必须将counter+=1放在else语句之外。否则,您将只设置2的倍数(一旦从counter+=1的循环中退出counter1)。

因此,此代码有效:

# set up loop
counter = 0
for x in list1:
    counter1 = 2
    if list1[counter] == 'P':
        for y in list1:
            number1 = counter * counter1
            if number1 < len(list1):
                list1[number1] = 'N'
                counter1 += 1
    counter += 1


此外,您应该使用enumeraterange简化代码:

# set up loop
for i, val in enumerate(list1):
    if val == 'P':
        for j in range(2, len(list1)):
            if i*j < len(list1):
                list1[i*j] = 'N'
            else:
                break


这是n = 12的结果:

 Enter a positive integer greater than or equal to 10: 12
 ['N', 'N', 'P', 'P', 'N', 'P', 'N', 'P', 'N', 'N', 'N', 'P', 'N']


编辑:将counter+=1放在else语句之外

关于python - 通过迭代更改列表的元素(python),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36829878/

10-15 18:50