简体   繁体   中英

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

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.

While you wanted to print c after every inner loop is finished:

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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