简体   繁体   中英

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,

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.

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 .

result = {}
for animal, value in data:
    result.setdefault(animal, []).append(value)
print(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM