Python修改错误的列表? [英] Python modifying wrong list?

查看:85
本文介绍了Python修改错误的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用方法生成素数列表.我需要遍历每个数字2 ... n,并检查2 ... n的倍数.由于某些原因,错误的清单似乎正在被修改.

I'm trying to generate a list of primes using the this method. I need to loop through every number 2...n and check it for multiples of 2...n. For some reason, the wrong list seems to be getting modified.

import sys
import argparse
import math

parser = argparse.ArgumentParser(description='find the largest prime factor of a number')
parser.add_argument('n', type=int, help='number')
args = parser.parse_args()

sieve = []
for i in range(2,args.n+1): sieve.append(i) # tried int(i)


copy1 = sieve # tried making extra copies. . .
copy2 = sieve
copy3 = sieve
#print int(math.sqrt(args.n))

for index, i in enumerate(copy1):
    #print index, i
    for ii in copy2:
        #print ii
        if i % ii == 0:
            sieve[index]= None


print sieve

我收到以下错误:

Traceback (most recent call last):  
  File "3.py", line 22, in <module>
    if i % ii == 0: TypeError: unsupported operand type(s) for %:
'int' and 'str'

推荐答案

您不制作副本.您正在使用引用,因此copy1copy2copy3都引用相同的列表-sieve.如果要复制,请使用:

You're not making copies. You're using references, so copy1, copy2, and copy3 all refer to the same list -- sieve. If you want to copy, use:

copy1 = sieve[:]

这将创建sieve的副本并将其分配给copy1.

which will create a copy of sieve and assign it to copy1.

这篇关于Python修改错误的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆