在 Python 中读取每行以冒号分隔的数据

编程入门 行业动态 更新时间:2024-10-14 20:27:18
本文介绍了在 Python 中读取每行以冒号分隔的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在创建一个程序,其中包含用户的姓名和他们在数据库中猜数字游戏的答案 - 类似于 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 20:06:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1398926.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:冒号   数据   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!