简体   繁体   中英

Print matching item in list python

I am just starting to learn python, I have a simple question.

l=['aa123','aa122','aa124','bb125','bb180']

#form above list i want to print a result as following:

Group 1
aa123
aa122
aa124

Group 2
bb125
bb180

and I want that if I update the list with 'cc000', it will print also a 'Group 3'

Thanks and regards, Giovanni

You can use a dictionary to better group your values:

import string
from collections import defaultdict
l=['aa123','aa122','aa124','bb125','bb180']
key = {a:b+1 for a, b in zip(string.ascii_lowercase, range(26))}
d = defaultdict(list)
for val in l:
   d[key[val[0]]].append(val)
for a, b in d.items():
   print("Group {}".format(a), b)

Output:

Group 1 ['aa123', 'aa122', 'aa124']
Group 2 ['bb125', 'bb180']

Or, using groupby in list comprehension:

import itertools
final_vals = {"Group {}".format(a):list(b) for a, b in itertools.groupby(sorted(l, key=lambda x:x[0]), key=lambda x:x[0])}
print(final_vals)

Output:

{'Group b': ['bb125', 'bb180'], 'Group a': ['aa123', 'aa122', 'aa124']}
i = ['bb334', 'aa341', 'cc555', 'aa342', 'aa337']
x = []

# Creating new ordered list
for j in range(0, 26):
    for k in i:
        if ord(k[0]) - 97 == j:
        x.append(k)

# Printing out list by groups
current_ord = ord(x[0][0])
counter = 1

print 'Group ' + str(counter) + ':'

for j in x:
    if ord(j[0]) != current_ord:
    current_ord = ord(j[0])
    counter += 1
        print '\nGroup ' + str(counter) + ':'

    print j

Kind of slow since you're doing an 26 * len(i) iterations to create the sorted list. I'm not sure if this answers your question fully... what happens when an item like 'ab111' is in the list? Will it ignore this?

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