['AAA_1p', 'AAA_2p', 'BBB_1p', 'CCC_1p', 'CCC_2p', 'CCC_3p']
From the list above
['AAA_2p', 'BBB_1p', 'CCC_3p']#Maximum number
['AAA_2p', 'BBB_1p', 'CCC_2p'] #2p, 1p (ignore 3p)
I want to take out two patterns of elements like this, but I can't think of any way to handle them.
Please let me know if there is a good way to deal with it.Thank you for your cooperation.
Here's how to use itertools.groupby().
>>>from ittertools import groupby
>>>lst=['AAA_1p', 'AAA_2p', 'BBB_1p', 'CCC_1p', 'CCC_2p', 'CCC_3p' ]
# the largest number
>>[list(g)[-1] for_, gin groupby(sorted(lst), lambdax:x.split('_')[0]]]
['AAA_2p', 'BBB_1p', 'CCC_3p']
# 2p for 2p, 1p for 1p (ignore 3p)
>>>
next((f'{k}_{i}p' for i in(2,1) if f'{k}_{i}p'ing))
for k, gin
((k, list(gp)) for k, gp in groupby (sorted(lst), lambdax:x.split('_')[0]))
if any((f'{k}_{i}p'ing for in (1,2))))
]
['AAA_2p', 'BBB_1p', 'CCC_2p']
As for the second process, we are considering the presence of elements that do not have _2p
or _1p
as suffixes.Examples include: (DDD_4p
)
['AAA_1p', 'AAA_2p', 'BBB_1p', 'CCC_1p', 'CCC_2p', 'CCC_3p', 'DDD_4p']
© 2025 OneMinuteCode. All rights reserved.