简体   繁体   中英

Find the largest size string in a list python?

I have a list as follows:

input1 = ['XS','S', 'M', 'L', 'XL', 'XXL', 'XXXL']

input2 = ['XS', 'S', 'M', 'L', 'XL', 'XS', 'S']

input3 = ['XS', 'S', 'M', 'L', 'S]

input4 = ['XS', 'S', 'M', 'L', 'XS', 'L']

etc.

As you see the list elements will change every time. I want to know how to find the largest element each time.

the standard list is this :

['XS','S', 'M', 'L', 'XL', 'XXL', 'XXXL']

This is what I have tried:

lst1 = {k:v for k, v in enumerate(['XS', 'S', 'M', 'L','XL','XXL', 'XXXL'])}

lst2 = ['XS', 'S', 'M', 'L', 'XL', 'XS', 'S']

tem = []

for i in lst2:
  for k,v in list(lst1.items()):
    if i == v:
      tem.append(k)


print(lst1[max(tem)])

But this is very complicated I guess. It should be much easier!

Just reverse the dictionary and use the get function as key to max :

lst1 = {v: k for k, v in enumerate(['XS', 'S', 'M', 'L','XL','XXL', 'XXXL']) }
lst2 = ['XS', 'S', 'M', 'L', 'XL', 'XS', 'S']

result = max(lst2, key=lst1.get)
print(result)

Output

XL

You don't need to overcomplicate stuff with dictionaries when simple string search would be enough.

lst1 = ['XS', 'S', 'M', 'L','XL','XXL', 'XXXL']
lst2 = ['XS', 'S', 'M', 'L', 'XL', 'XS', 'S']

result = next(x for x in lst1[::-1] if x in lst2)

If you don't want to reverse the list, just create on opposite order

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