如何制作动态列表然后将其打印出来,这个例子只是我想要做的事情,列表可能有数百个。
但我想要任何有猫打印的东西" cat"与其下面列出的任何值相关联,
data = [[" cat"," one"],[" dog"," one"],[&#34 ; cat"," ten"],[" frog"," one"],[" dog","十","绿色"]]
#Would like this to print out like:
cat
one
ten
dog
one
ten
green
frog
one
答案 0 :(得分:6)
您可以使用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)
答案 1 :(得分:0)
您也可以使用setdefault
。
result = {}
for animal, value in data:
result.setdefault(animal, []).append(value)
print(result)