我有一个简单的代码:
with open('trace.txt') as inf:
for line in inf:
parts = line.split()
lines = float(parts[1])
print lines[0]
但由于无法访问列表中的浮点数,我收到错误:
TypeError: 'float' object has no attribute '__getitem__'
错误的最佳解释是什么以及如何解决此问题?
答案 0 :(得分:1)
你不能打印浮动元素,因为float不是列表,因此不实现__getitem __。
lines = []
with open('trace.txt') as inf:
for line in inf:
parts = line
lines.append(float(parts[1]))
print lines[0]
如果要打印列表中的元素,可以使用索引访问它。
答案 1 :(得分:0)
问题是你在每次循环迭代时用float的值覆盖变量lines
。相反,您希望将其附加到名为lines
的列表中:
lines = []
with open('trace.txt') as inf:
for line in inf:
parts = line.split()
lines.append(float(parts[1]))
print lines[0]
答案 2 :(得分:0)
with open('trace.txt') as inf:
lines = [float(parts[1]) for line in inf for parts in line.split()]
print lines[0]