希望我在标题中已经解释得很好,但这就是我所拥有的:
输入数据:
Mushroom Kingdom, Mario
Hyrule, Link
Mushroom Kingdom, Bowser
Zebes, Samus
Zebes, Metroid
我想要运行这样的东西,
# The next three lines establish that I'll be reading proc as a file
import subprocess
cmd = 'external command that returns the above data'
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
homeworlds = {}
while True:
line = proc.stdout.readline().split(',')
if line:
# If line isn't empty
homeword = line[0]
person = line[1]
homeworlds[homeword] = list.append[person] # Good logic? Bad syntax?
else:
break
目标是我可以打电话:
print homeworlds['Mushroom Kingdom']
并返回列表
Mario, Bowser
答案 0 :(得分:3)
在这里使用defaultdict
会更容易。此外,您当前正在调用split()
而没有任何参数。你真正想要做的是分开,
。所以你应该致电split(',')
。
所以你的代码应该看起来像这样:
homeworlds = collections.defaultdict(list)
while True:
line = proc.stdout.readline().split(',')
if line:
# If line isn't empty
homeworld = line[0].strip()
person = line[1].strip()
homeworlds[homeworld].append(person)
else:
break
答案 1 :(得分:2)
if not homeword in homeworlds:
homeworlds[homeword] = list()
homeworlds[homeword].append(person)
答案 2 :(得分:1)
使用defaultdict
from collections import defaultdict
homeworlds = defaultdict(list)
homeworlds[homeword].append(person)
答案 3 :(得分:0)
试试这个:
if homeword not in homeworlds:
homeworlds[homeword] = []
homeworlds[homeword].append(person)
这会检查homeword
中是否有homeworld
的条目。如果没有,它会在那里添加一个列表。然后我们肯定知道我们在homeworld[homeword]
有一个列表,因此我们可以在其上调用.append(person)
。
答案 4 :(得分:0)
以下是一致且优雅的解决方案(部分灵感来自其他答案):
#!/bin/env python
from collections import defaultdict
lines = """Mushroom Kingdom, Mario
Hyrule, Link
Mushroom Kingdom, Bowser
Zebes, Samus
Zebes, Metroid
"""
homeworlds = defaultdict(list)
for line in lines.splitlines():
if line and ',' in line:
key, value = line.split(',')
homeworlds[key].append(value.trim())
print(homeworlds)
答案 5 :(得分:0)
Python 2.7.3rc2 (default, Apr 22 2012, 22:30:17)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> input_data = [('Mushroom Kingdom', 'Mario'),
... ('Hyrule', 'Link'),
... ('Mushroom Kingdom', 'Bowser'),
... ('Zebes', 'Samus'),
... ('Zebes', 'Metroid')]
>>> homeworlds = {}
>>> for homeword,person in input_data:
... homeworlds.setdefault(homeword, []).append(person)
...
>>> homeworlds
{'Hyrule': ['Link'], 'Zebes': ['Samus', 'Metroid'], 'Mushroom Kingdom': ['Mario', 'Bowser']}
>>> print(homeworlds['Mushroom Kingdom'])
['Mario', 'Bowser']
>>> print("{0}".format(', '.join(homeworlds['Mushroom Kingdom'])))
Mario, Bowser
在你的情况下交换for循环:'input'数据为'line'