为什么我只能获得[-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
答案 0 :(得分:1)
发帖时有些事情搞砸了。
我猜你有这个:
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
:
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
答案 1 :(得分:1)
我不确定此代码的上下文,但您可以通过删除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
并直接打印,可以进一步减少这种情况:
f = open('Qin.txt')
for line in f:
Z = float(line)
print [i-Z for i in range(1, 6)]