简体   繁体   English

循环一些输入数据后,循环并编辑列表中的项目

[英]Loop over and editing the items in a list after looping over some input data

Why can i only get the [-1.0,0.0,1.0,2.0,3.0], instead of [0.0,1.0,2.0,3.0,4.0] [-2.0,-1.0,0.0,1.0,2.0] [-1.0,0.0,1.0,2.0,3.0], thank you 为什么我只能得到[-1.0,0.0,1.0,2.0,3.0],而不是[0.0,1.0,2.0,3.0,4.0] [-2.0,-1.0,0.0,1.0,2.0] [-1.0,0.0] ,1.0,2.0,3.0],谢谢

V = [1,2,3,4,5]
f = open('Qin.txt')             # values in Qin.txt: 1
    for line in iter(f):                             3
    Z = float(line)                                  2

    c = []
    for i in range(len(V)):
    c.append(V[i]-Z)

    print c

Something was messed up while you were posting. 在发帖时,有些东西搞砸了。

I guess you have this: 我想你有这个:

V = [1,2,3,4,5]
f = open('Qin.txt')             # values in Qin.txt: 1
for line in iter(f):                                 3
    Z = float(line)                                  2

    c = []
    for i in range(len(V)):
        c.append(V[i]-Z)

print c

Therefore, the print c is called only once, after the outer loop has finished. 因此,在外环完成后,只print c一次print c

While you wanted to print c after every inner loop is finished: 虽然你想在每个内循环完成后print c

V = [1,2,3,4,5]
f = open('Qin.txt')             # values in Qin.txt: 1
for line in iter(f):                                 3
    Z = float(line)                                  2

    c = []
    for i in range(len(V)):
        c.append(V[i]-Z)

    print c

I'm unsure of the context of this code, but you can simplify your code snippet somewhat by removing the iter() (a file object is already iterable) and the range(len(V)) : 我不确定此代码的上下文,但您可以通过删除iter() (文件对象已经可迭代)和range(len(V))稍微简化您的代码片段:

f = open('Qin.txt')

for line in f:
    Z = float(line)
    c = []
    for i in range(1, 6):
        c.append(i - Z)
    print c

That can further be reduced by building the list c with a list comprehension and printing it directly: 通过使用列表c构建列表c并直接打印,可以进一步减少这种情况:

f = open('Qin.txt')
for line in f:
    Z = float(line)
    print [i-Z for i in range(1, 6)]

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

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