Reputation: 55
I'm trying make a if, elif list comprehension line... found this code in other question:
>>> l = [1, 2, 3, 4, 5]
>>> ['yes' if v == 1 else 'no' if v == 2 else 'idle' for v in l]
['yes', 'no', 'idle', 'idle', 'idle']
My question is: Can I pass the last 'else' as a third action? I've tried use pass but got a syntax error.
I have this:
# list = [(code, qty),(code, qty)]
>>>storehouse = [('BSA2199',2000),('PPF5239',251),('BSA1212',989)]
>>>buyList = [(cod, 1000) if qty < 200 else (cod, 500) for cod, qty
in storehouse]
I want to ignore the items that are > 1000.
Thanks, hope I had made my self clear(first question in here).
Upvotes: 1
Views: 82
Reputation: 71454
I might encode this relationship in a dictionary so you can use it for both the filtering and the mapping:
>>> l = [1, 2, 3, 4, 5]
>>> d = {1: 'yes', 2: 'no'}
>>> [d[v] for v in l if v in d]
['yes', 'no']
Upvotes: 1
Reputation: 77837
You need to first filter for the desired values, at the outer for
expression.
Within that, you choose your yes/no response:
['yes' if v == 1 else 'no'
for v in l if v in [1, 2]]
Output:
['yes', 'no']
Upvotes: 1