我有一个看起来像这样的文本文件:
John Graham 2
Marcus Bishop 0
Bob Hamilton 1
... and like 20 other names.
每个名称出现几次,后面有不同的数字(分数)。 我需要制作一个列表,只显示每个名称一次,并在其后显示该名称的总分。我需要使用字典。
这就是我所做的,但它只是从一开始就像文本文件那样生成一个列表:
dict = {}
with open('scores.txt', 'r+') as f:
data = f.readlines()
for line in data:
nameScore = line.split()
print (nameScore)
我不知道如何做下一部分。
答案 0 :(得分:5)
以下是使用defaultdict(int)
的一个选项:
from collections import defaultdict
result = defaultdict(int)
with open('scores.txt', 'r') as f:
for line in f:
key, value = line.rsplit(' ', 1)
result[key] += int(value.strip())
print result
如果scores.txt
的内容是:
John Graham 2
Marcus Bishop 0
Bob Hamilton 1
John Graham 3
Marcus Bishop 10
打印:
defaultdict(<type 'int'>,
{'Bob Hamilton': 1, 'John Graham': 5, 'Marcus Bishop': 10})
UPD(格式化输出):
for key, value in result.iteritems():
print key, value
答案 1 :(得分:1)
我的第一次传球看起来像是:
scores = {} # Not `dict`. Don't reuse builtin names.
with open('scores.txt', 'r') as f: # Not "r+" unless you want to write later
for line in f:
name, score = line.strip().rsplit(' ', 1)
score = int(score)
if name in scores:
scores[name] = scores[name] + score
else:
scores[name] = score
print scores.items()
这不完全是我写的方式,但我想明确表示你可以跟随。
答案 2 :(得分:0)
使用字典get:
dict = {}
with open('file.txt', 'r+') as f:
data = f.readlines()
for line in data:
nameScore = line.split()
l=len(nameScore)
n=" ".join(nameScore[:l-1])
dict[n] = dict.get(n,0) + int(nameScore[-1])
print dict
输出:
{'Bob Hamilton': 1, 'John Graham': 2, 'Marcus Bishop': 0}
答案 3 :(得分:0)
我遇到了类似的情况。我修改了Wesley's代码以适应我的具体情况。我有一个映射文件&#34; sort.txt&#34;它由不同的.pdf文件和数字组成,用于根据网站DOM操作的输出指示我想要的顺序。我想将所有这些单独的pdf文件合并到一个pdf文件中,但我想保留它们在网站上的相同顺序。所以我想根据导航菜单中的树位置添加数字。
1054 spellchecking.pdf
1055 using-macros-in-the-editor.pdf
1056 binding-macros-with-keyboard-shortcuts.pdf
1057 editing-macros.pdf
1058 etc........
以下是我提出的代码:
import os, sys
# A dict with keys being the old filenames and values being the new filenames
mapping = {}
# Read through the mapping file line-by-line and populate 'mapping'
with open('sort.txt') as mapping_file:
for line in mapping_file:
# Split the line along whitespace
# Note: this fails if your filenames have whitespace
new_name, old_name = line.split()
mapping[old_name] = new_name
# List the files in the current directory
for filename in os.listdir('.'):
root, extension = os.path.splitext(filename)
#rename, put number first to allow for sorting by name and
#then append original filename +e extension
if filename in mapping:
print "yay" #to make coding fun
os.rename(filename, mapping[filename] + filename + extension)
我没有像_full那样的后缀,所以我不需要那些代码。除了相同的代码之外,我从未真正触及过python,所以这对我来说是一次很好的学习经历。