在 Python 中读取每行以冒号分隔的数据 [英] Reading data separated by colon per line in Python

查看:143
本文介绍了在 Python 中读取每行以冒号分隔的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个程序,其中包含用户的姓名和他们在数据库中猜数字游戏的答案 - 类似于 Python 上的格式.我创建了一个文本文件,其中包含所有用户的数据,格式为:guess.例如,

I'm creating a program that has the user's name and their answers to a guess the number game in a database - like format on Python. I have created a text file where all of the users' data is, in the form name : guess. For instance,

Dave:23
Adam:12
Jack:13
Dave:25
Adam:34

现在,我试图将文件作为元组重新读入 Python,所以我决定使用下面的代码行(真正的答案是 17):

Now, I am trying to re - read the file into Python as a tuple, so I decided to use the line of code below (The real answer is 17):

dict(line.split(':', 1) for line in open('guesses.txt'))

但这只会在 IDLE 中返回一个空行.
为什么这不起作用?
为了让它更简单,我需要一个包含用户名和他们猜测的元组.

But this will just hand me back an empty line in the IDLE.
Why is this not working?
To make it more simple, I need a tuple that has the user's name and then their guesses.

我的字典应该是这样的:

My dictionary should look like this:

{'Dave': 23 25, 'Jack' : 13, 'Adam' : 13 34}

谢谢,德尔伯特.

推荐答案

使用 defaultdict 并将值存储在列表中:

Use a defaultdict and store values in a list:

s="""Dave:23
Adam:12
Jack:13
Dave:25
Adam:34
"""

from collections import defaultdict
d = defaultdict(list)

for line in s.splitlines():
    name,val = line.split(":")
    d[name].append(int(val))

print(d)
defaultdict(<class 'list'>, {'Jack': [13], 'Adam': [12, 34], 'Dave': [23, 25]})

所以对你的文件做同样的事情:

So for your file just do the same:

d = defaultdict(list)
with open('guesses.txt') as f:
    for line in f:
        name,val = line.split(":")
        d[name].append(int(val))

您自己的代码应该返回 {'Jack': '13', 'Dave': '25', 'Adam': '34'} 其中 Dave 和 Adam 的值被覆盖在最后两行中,因此需要将值存储在列表中并附加.

Your own code should return {'Jack': '13', 'Dave': '25', 'Adam': '34'} where the the values for Dave and Adam are overwritten in the last two lines hence the need to store values in a list and append.

您也不能使用您在答案中提到的元组,每次要添加新值时都必须创建新元组,因为元组不可变.

You also cannot use tuples as you mentioned in your answer without creating new tuples each time you want to add a new value as tuples are immutable.

如果您不想要 defaultdict(,)

from pprint import pprint as pp

pp(d)
{'Adam': ['12', '34'],
 'Dave': ['23', '25'],
 'Jack': ['13']}

这篇关于在 Python 中读取每行以冒号分隔的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆