gpt4 book ai didi

python - 创建列表字典

转载 作者:行者123 更新时间:2023-11-28 21:27:03 26 4
gpt4 key购买 nike

希望我已经在标题中解释得足够好,但这是我所拥有的:

输入数据:

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

最佳答案

使用 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

关于python - 创建列表字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11725905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com