Python 从列表到字典的转换迭代输出
这是我的输入txt文件的摘录(完整文件有大约8k个观察值),包含3个元素(名称、某些标识符、年份),由制表符分隔:Python 从列表到字典的转换迭代输出,python,python-2.7,list,loops,Python,Python 2.7,List,Loops,这是我的输入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')
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'}
我不确定为什么输出会给出第一项的结果,然后是第二项的结果。我只需要输出生成的最后一行。你知道我应该怎么做吗?你是在循环的每次迭代中打印字典,而不是在循环之后。只需将其缩进即可:
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
在循环的每次迭代中而不是在循环之后打印字典。只需将其缩进即可:
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