【问题标题】:text file to empty dictionary文本文件到空字典
【发布时间】:2021-11-25 04:52:41
【问题描述】:
dictionary = {}
file = 'lightning.txt'
with open(file) as d:
    for line in d:
        pa = line.split()
        dictionary[pa[0]] = pa[1:]

print(dictionary)

我有一个显示闪电球员及其进球和助攻的文本文件,它的设置如下:

Stamkos
46
50
Hedman
30
50
Point
40
50

所有内容都在单独的行中,我正在尝试编写一个将此文本文件发送到字典的程序,尽管我的输出未显示我想要的方式。字典以{'Stamkos': [], '46': [], '50': [], 的形式出现,我试图摆脱空列表,只将名称作为键,将目标和助攻作为值,但没有任何效果。

【问题讨论】:

  • question 有帮助吗?
  • 想要的结果是什么?

标签: python dictionary text-files


【解决方案1】:

问题是值在不同的行中。使用next 获取其他的:

dictionary = {}
file = 'lightning.txt'
with open(file) as d:
    for line in d:
        dictionary[line.strip()] = [next(d).strip(), next(d).strip()]

print(dictionary)

输出

{'Stamkos': ['46', '50'], 'Hedman': ['30', '50'], 'Point': ['40', '50']}

【讨论】:

  • 这有帮助,谢谢!
  • @Imbadatcoding 我的回答对您有帮助,请考虑接受。因此它可以向其他人表明您的问题已解决
【解决方案2】:

您可以使用 zip 一次将 3 行读入 3 个单独的变量:

players = dict()
with open("lightning.txt","r") as f:
    for name,goals,assists in zip(f,f,f):
        players[name.strip()] = [int(goals),int(assists)]

print(players)
{'Stamkos': [46, 50], 'Hedman': [30, 50], 'Point': [40, 50]}

或者在字典理解中:

with open("lightning.txt","r") as f:
    players = {name.strip():[*map(int,stats)] for name,*stats in zip(f,f,f)}

或者一个(神秘的)拉链映射:

with open("lightning.txt","r") as f:
    players = dict(zip(map(str.strip,f),zip(*[map(int,f)]*2)))

您还可以将数据构建为嵌套字典:

players = dict()
with open("lightning.txt","r") as f:
    for name,goals,assists in zip(f,f,f):
        players[name.strip()] = {"goals":int(goals),"assists":int(assists)}

print(players)
{'Stamkos': {'goals': 46, 'assists': 50}, 
 'Hedman': {'goals': 30, 'assists': 50}, 
 'Point': {'goals': 40, 'assists': 50}}

【讨论】:

    【解决方案3】:

    另一种将数字转换为整数的方法:

    file = 'lightning.txt'
    with open(file) as d:
        names = map(str.strip, d)
        ints = map(int, d)
        dictionary = {name: [next(ints), next(ints)]
                      for name in names}
    

    结果(Try it online!):

    {'Stamkos': [46, 50], 'Hedman': [30, 50], 'Point': [40, 50]}
    

    【讨论】:

      猜你喜欢
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      相关资源
      最近更新 更多