简体   繁体   English

使用 for 遍历列表不是从索引开始

[英]Iterating with for through a list isn't starting at the index

I have a list of primes that I am importing from a text file.我有一个从文本文件导入的素数列表。 When I iterate through the list with for, it starts at the third member, but when I use a while loop this problem doesn't occur.当我用 for 遍历列表时,它从第三个成员开始,但是当我使用 while 循环时,这个问题不会发生。 My code so far is this:到目前为止,我的代码是这样的:

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])

I want to know why this happens, if there's a problem when creating the list or if there's any way to fix it.我想知道为什么会发生这种情况,是否在创建列表时出现问题或者是否有任何方法可以修复它。

Here you iterate over z, which starts at 0, so its prints the primes correctly, since the first prime (primes[0]) is 2在这里迭代从 0 开始的 z,因此它正确打印素数,因为第一个素数 (primes[0]) 是 2

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

In the second Block you iterate over the actual prime numbers, so the first print contains primes[2].在第二个块中迭代实际的素数,所以第一个打印包含素数[2]。 So it starts with the 3rd prime number.所以它从第三个素数开始。

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

在第二个循环中,您需要说print(x)而不是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()

There exists a method in python called .readlines() that you can apply on file objects and it returns a list for you of all lines in your text file. python 中存在一个名为 .readlines() 的方法,您可以将其应用于文件对象,它会为您返回文本文件中所有行的列表。 Happy to help!乐于帮助!

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

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