[英]Making dynamic lists to print out variables
How can I make a dynamic list and then print it out, this example is just an idea of what I want to do, the lists could be in the hundreds. 我如何制作一个动态列表,然后打印出来,这个例子只是我要做什么的一个想法,列表可能有数百个。
But I want anything that has cat to print "cat" with any value associated with it listed below it, 但是我希望任何具有cat的东西都可以打印“ cat”,并在其下面列出与之相关的任何值,
data = [["cat","one"], ["dog", "one"], ["cat", "ten"], ["frog", "one"], ["dog", "ten", "green"]] 数据= [[“猫”,“一个”],[“狗”,“一个”],[“猫”,“十”],[“青蛙”,“一个”],[“狗”,“十“, “绿色”]]
#Would like this to print out like:
cat
one
ten
dog
one
ten
green
frog
one
You can use a defaultdict. 您可以使用defaultdict。
from collections import defaultdict
groups = defaultdict(list)
for animal, value in data:
groups[animal].append(value)
for animal, values in groups.items():
print(animal)
for value in values:
print(value)
You can also use setdefault
. 您也可以使用
setdefault
。
result = {}
for animal, value in data:
result.setdefault(animal, []).append(value)
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.