python无法从lis访问值

2024-04-26 01:05:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的代码:

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__'

对这个错误最好的解释是什么?如何解决这个问题?你知道吗


Tags: 代码intxtforas错误withline
3条回答

问题是每次循环迭代都要用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]
with open('trace.txt') as inf:
    lines = [float(parts[1]) for line in inf for parts in line.split()]
print lines[0]

您不能打印float的元素,因为float不是一个列表,因此不实现\uu getitem\uuuu。你知道吗

lines = []
with open('trace.txt') as inf:
    for line in inf:
        parts = line
        lines.append(float(parts[1]))

print lines[0]

如果要打印列表中的元素,可以使用索引访问它。你知道吗

相关问题 更多 >

    热门问题