简体   繁体   中英

Printing list items by group in python

I'm still new to Python. I have similar list to the below list:

items = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]

I'm trying to print it by grouping the first item together and get something like this:

4 : ['A', 'B']
5 : ['C', 'D', 'E']
6 : ['F', 'G']

How do I do this?

output = {}

items = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]

for number, letter in items:
    if number not in output:
        output[number] = []
    output[number].append(letter)


print('\n'.join(f'{number} : {letters}' for number, letters in output.items()))

Output

4 : ['A', 'B']
5 : ['C', 'D', 'E']
6 : ['F', 'G']

Explanation

  • I use the name items rather than list so as to not conflict with the stdlib list .
  • I unpack the number and letter into two variables whilst looping through the items.
  • For each item, I check whether it already exists as a key in the output. If not, I instantiate an empty list.*
  • I append the letter into its corresponding list.

* I would recommend using collections.defaultdict for this to simplify your code.

Here is a simple solution (but slow for big lists) that does not require any external package:

res = {}
for k,v in items:
    res[k] = res.get(k, []) + [v]
print('\n'.join(f'{k} : {res[k]}' for k in res))

You can use itertools.groupby and operator.itemgetter :

>>> from itertools import groupby
>>> from operator import itemgetter
>>> list_ = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]
>>> print(*(f'{k}: {sum(list(g), [])}' 
            for k, g in groupby(list_, key=lambda x: list.pop(x, 0))), 
           sep='\n')
4: ['A', 'B']
5: ['C', 'D', 'E']
6: ['F', 'G']

If you want to do this without importing anything:

>>> list_ = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]

>>> table = {}

>>> for key, value in list_:
        table.setdefault(key, []).append(value)
    

>>> table
{4: ['A', 'B'], 5: ['C', 'D', 'E'], 6: ['F', 'G']}

>>> for key, group in table.items():
        print(f'{key}: {group}')
    
4: ['A', 'B']
5: ['C', 'D', 'E']
6: ['F', 'G']

You can use the dictionary methodsetdefault for this. It works like this:
If the key is in the dictionary, return its value. If not, insert the key with a value of default(empty list in this case) and return default( list ).

result = {}
for item in items:
    result.setdefault(item[0], []).append(item[1])

print(result)

Output:

{4: ['A', 'B'], 5: ['C', 'D', 'E'], 6: ['F', 'G']}

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