Python 3.4 : Lists stored in a file - Iterating over characters instead of list items

标签 python

我有一个像这样的文件(myfile)

['user1', 1,2]
['user2',5,1]
['user3',1,2]

我想迭代文件中列表中的每个项目。我的代码如下

with open(myfile) as f:
    for line in f:
        for items in list(line):
            print(items)

它打印每个字符而不是每个单词。请帮忙。

最佳答案

您将这些行作为字符串而不是列表来读取。为了提高安全性,eval()ast.literal_eval() 应该在这里实现:

with open(myfile) as f:
    for line in f:
        for items in eval(line):
            print(items)

或更安全(感谢@JaredGoguen):

import ast
with open(myfile) as f:
    for line in f:
        for items in ast.literal_eval(line):
            print(items)

希望有帮助!

关于Python 3.4 : Lists stored in a file - Iterating over characters instead of list items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37240423/

相关文章:

python-jira获取json

python - AWS Lambda 未检测到 pyopenssl

python - 添加许多具有重叠索引和列的 pandas 数据框

python - 在 Python 文档中嵌入图像

python - Google App Engine 内存使用率异常高

python - 如何在python中将long列表转换为逗号分隔的字符串

python - 获取numpy矩阵中正方形的坐标

python - Django filter_horizo​​ntal 用于多对一关系

python - 将缺失值附加到 CSV 文件

python - 优雅地在列表中查找子列表