[英]Loop over and editing the items in a list after looping over some input data
为什么我只能得到[-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
在发帖时,有些东西搞砸了。
我想你有这个:
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
因此,在外环完成后,只print c
一次print c
。
虽然你想在每个内循环完成后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
我不确定此代码的上下文,但您可以通过删除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
通过使用列表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.