简体   繁体   中英

Convert for loop to list comprehension

I am trying to convert my code to a list comprehension, but cannot figure this out

my code:

dicts = [
    {"p": 1, "p": 2, "olp": 3, "r": 4}, 
    {"s": 1, "o": 2, "e": 3, "cs": 4}, 
    {"vc":1, "txc":2, "faw":3, "e": 4}
]

l = []

for d in dicts:
    for k, v in sorted(d.items(), key=lambda kv: kv[1]):
        if v % 4 == 0:
            if len(k) > 1:
                l.append(k[1])
            else:
                l.append(k)
        elif v % 2 == 0:
            if len(k) > 2:
                l.append(k[0])
            else:
                l.append(k)
print(''.join(l))

I've tried this, but doesn't work, can you help me with it?

l = [
    k[0] if len(k)>2 else k elif v % 2 == 0 
    k[1] if len(k)>1 else k if k % 4 == 0  
    for k,v in sorted(d.items(), key=lambda kv: kv[1]) for d in dicts
]

Expected output for l :

['p', 'r', 'o', 's', 't', 'e']

Reformatted into a one-line list-comprehension, the code is as follows:

>>> l = [k[1] if v%4 == 0 and len(k) > 1 else k[0] if len(k) > 2 else k for d in dicts for k,v in sorted(d.items(), key=lambda kv: kv[1]) if v%2 == 0]
>>> l
['p', 'r', 'o', 's', 't', 'e']

Or formatted a bit more nicely:

l = [
     k[1] if v%4 == 0 and len(k) > 1
     else k[0] if len(k) > 2 
     else k
     for d in dicts
     for k,v in sorted(d.items(), key=lambda kv: kv[1])
     if v%2 == 0
     ]

As far as I can tell, you don't need to call sorted() on d.items() either, so you could omit that unless it's needed outside your MWE.

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