Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在列表中使用for进行迭代不是';t从索引开始_Python_Python 3.x_List - Fatal编程技术网

Python 在列表中使用for进行迭代不是';t从索引开始

Python 在列表中使用for进行迭代不是';t从索引开始,python,python-3.x,list,Python,Python 3.x,List,我有一个从文本文件导入的素数列表。当我使用for遍历列表时,它从第三个成员开始,但是当我使用while循环时,这个问题不会发生。到目前为止,我的代码是: with open("primes.txt", "r") as f: primes = list(f) primes = [int(i) for i in primes] z = 0 while z < 10: #here it starts printing

我有一个从文本文件导入的素数列表。当我使用for遍历列表时,它从第三个成员开始,但是当我使用while循环时,这个问题不会发生。到目前为止,我的代码是:

with open("primes.txt", "r") as f:
    primes = list(f)

primes = [int(i) for i in primes]

z = 0

while z < 10:              #here it starts printing "2,3,5,7,11,..."
    print(primes[z])
    z += 1

for x in primes:           #here it starts printing "5,7,11,..."
    print(primes[x])

以open(“primes.txt”、“r”)作为f的
:
素数=列表(f)
素数=[int(i)表示素数中的i]
z=0
当z<10时:#这里开始打印“2,3,5,7,11,…”
打印(素数[z])
z+=1
对于素数中的x:#这里开始打印“5,7,11,…”
打印(素数[x])

我想知道为什么会发生这种情况,如果在创建列表时出现问题,或者是否有任何方法可以解决它。

这里你迭代z,它从0开始,因此它正确地打印素数,因为第一个素数(素数[0])是2


在第二个循环中,您需要说
print(x)
,而不是
print(primes[x])


python中有一个名为.readlines()的方法,可以应用于文件对象,它会为您返回文本文件中所有行的列表。很乐意帮忙

因为循环中有
print(primes[x])
,而不是
print(x)
。你在打印第二个素数,第三个素数,第五个素数,第七个素数。我打赌你不是真的在打印11,而是跳到了13。真是个简单的错误。谢谢你帮助我这样的笨蛋!(你是对的,它跳到13)一个容易犯的错误,特别是因为你在第一个循环中有
print(primes[z])
。有时只需要第二双眼睛。
while z < 10:              #here it starts printing "2,3,5,7,11,..."
print(primes[z])
z += 1
for x in primes:           #here it starts printing "5,7,11,..."
print(primes[x])
with open('primes.txt', 'r') as f:
# size_to_read = 100
f_content = f.readlines()
print(f_content)
primes = [int(i) for i in f_content]
# f.close()
for prime in primes:
    print(prime)
f.close()