【问题标题】:Output iterated from converting list to dictionary从将列表转换为字典的输出迭代
【发布时间】:2017-10-10 17:04:39
【问题描述】:

这是我的输入 txt 文件的摘录(完整文件有大约 8k 观察),包含 3 个元素(名称、某些标识符、年份),由制表符分隔:

steve jobs      7653596   2007
john hancock    7653596   2007

我尝试将列表放入字典中:

dictList = []
with open('filename.txt') as fo:
    for line in fo:
        elements = line.rstrip().split('\t')[0:]
        dictList.append(dict(zip(elements[0::3], elements[1::2])))
        print dictList

上面执行后的输出:

{'steve jobs': '7653596'}
{'steve jobs': '7653596', 'john hancock': '7653596'}

我不确定为什么输出给我的是第一项的结果,然后是第二项的结果。我只需要从输出生成的最后一行。知道我应该怎么做吗?

【问题讨论】:

    标签: python python-2.7 list loops


    【解决方案1】:

    您在循环的每次迭代而不是在循环之后打印字典。缩进它,你应该没问题:

    dictList = []
    with open('filename.txt') as fo:
        for line in fo:
            elements = line.rstrip().split('\t')[0:]
            dictList.append(dict(zip(elements[0::3], elements[1::2])))
    
        print dictList # Here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2021-10-13
      • 2020-10-06
      • 1970-01-01
      相关资源
      最近更新 更多