简体   繁体   English

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

[英]Reading data separated by colon per line in Python

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. 我正在创建一个程序,该程序具有用户名以及他们对数据库中数字游戏的猜测的答案-如Python上的格式。 I have created a text file where all of the users' data is, in the form name : guess. 我创建了一个文本文件,其中所有用户数据都以name:guess的形式存在。 For instance, 例如,

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

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): 现在,我试图将文件作为一个元组重新读入Python,所以我决定使用下面的代码行(真正的答案是17):

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

But this will just hand me back an empty line in the IDLE. 但这只会使我退回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}

Thanks, Delbert. 谢谢,德尔伯特。

from collections import defaultdict

result = defaultdict(list)
with open("guesses.txt") as inf:
    for line in inf:
        name, score = line.split(":", 1)
        result[name].append(int(score))

which gets you 这让你

# result
{ "Dave": [23, 25], "Jack": [13], "Adam": [12, 34] }

Use a defaultdict and store values in a list: 使用defaultdict并将值存储在列表中:

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))

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. 您自己的代码应返回{'Jack': '13', 'Dave': '25', 'Adam': '34'} ,其中Dave和Adam的值在最后两行被覆盖,因此需要存储列表中的值并追加。

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 . 由于元组是不可变的,因此每次您要添加新值时也不能创建新元组,就不能使用答案中提到的元组。

You can print(dict(d)) or use pprint if you don't want the defaultdict(<class 'list'>,) 如果不想使用defaultdict(<class 'list'>,) pprint defaultdict(<class 'list'>,)可以print(dict(d))或使用pprint

from pprint import pprint as pp

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM