简体   繁体   English

通过迭代更改列表的元素(python)

[英]Changing the elements of a list by iteration (python)

I'm trying to iterate through a list (range entered by user), at first assume that all numbers are prime (P), and have the program iterate through the list. 我正在尝试迭代列表(用户输入的范围),首先假设所有数字都是素数(P),并让程序遍历列表。 When the element in the list is P, I want to iterate through all multiples within the range and change them to N. When the element is N, I want the program to move onto the next number (I set 0 and 1 to not prime, as they are exceptions). 当列表中的元素是P时,我想迭代范围内的所有倍数并将它们更改为N.当元素为N时,我希望程序移动到下一个数字(我将0和1设置为不是素数,因为他们是例外)。 I'm running into an issue with indexing however, I get the error: 我遇到了索引问题,但是我得到了错误:

 list1[number1] = 'N'
IndexError: list assignment index out of range

When I run the program I have. 当我运行程序时,我有。 Here is the code: 这是代码:

# 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 

Any help would be appreciated! 任何帮助,将不胜感激! Thanks. 谢谢。

In your loops, you're setting only squared value as non prime because you iterate counter in counter1 's loop. 在循环中,您只将平方值设置为非素数,因为您在counter1的循环中迭代counter

Then you have to check if number1 is lesser than the size of list1 . 然后你必须检查number1是否小于list1的大小。

You also have to put counter+=1 outside else statement. 你还必须将counter+=1置于else语句之外。 Otherwise you'll set only multiples of 2 (once you withdraw counter+=1 from counter1 's loop). 否则你只会设置2的倍数(一旦你从counter1的循环中撤回counter+=1 )。

So this code works: 所以这段代码有效:

# 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

Besides, you should simplify your code using enumerate and range : 此外,您应该使用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

Here's the result for n = 12: 这是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']

Edit: Put counter+=1 outside else statement 编辑:在其他语句之外加上counter+=1

list1[number1] = 'N'
IndexError: list assignment index out of range

That means that number1 is a bigger number than the total amount of items in the list. 这意味着number1的数量大于列表中项目的总数。

The problem is in the line number1 = counter * counter1 . 问题在于行号1 number1 = counter * counter1 Lets say are 10 items in list1, by the time you got to using the number 10 as the counter you are going to be trying to access the 100th item in the list even though there are only 10 items in there. 让我们说list1中有10个项目,当你使用数字10作为计数器时,你将试图访问列表中的第100个项目,即使那里只有10个项目。 (counter * counter1 or 10 * 10 = 100 (actually the counter starts at 2 so it would be an even bigger number, but you get the point)) (计数器* counter1或10 * 10 = 100(实际上计数器从2开始,因此它将是一个更大的数字,但你明白了))

Also a nice little hint. 也是一个不错的小提示。 Implementing a Sieve of Eratosthenes algorithm instead will greatly speed things up. 实施Eratosthenes算法筛选将大大加快速度。

You may update your code like this: 您可以像这样更新您的代码:

# set up loop
for counter in range(len(list1)):
    if list1[counter] == 'P':
        number1 = 2 * counter
        while number1 < new_n:
            list1[number1] = 'N'
            number1 += counter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM