我如何通过列表理解中的最后一个
How do i pass the last else in list comprehension
我正在尝试制作一个 if, elif 列表理解线...在其他问题中找到此代码:
>>> 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']
我的问题是:我可以通过最后一个 'else' 作为第三个动作吗?
我试过使用 pass 但出现语法错误。
我有这个:
# 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]
我想忽略大于 1000 的项目。
谢谢,希望我已经说清楚了(这里的第一个问题)。
您需要首先 在外部for
表达式中过滤所需的值。
在其中,您选择 yes/no 回复:
['yes' if v == 1 else 'no'
for v in l if v in [1, 2]]
输出:
['yes', 'no']
我可能会在字典中对这种关系进行编码,以便您可以将其用于过滤和映射:
>>> l = [1, 2, 3, 4, 5]
>>> d = {1: 'yes', 2: 'no'}
>>> [d[v] for v in l if v in d]
['yes', 'no']
我正在尝试制作一个 if, elif 列表理解线...在其他问题中找到此代码:
>>> 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']
我的问题是:我可以通过最后一个 'else' 作为第三个动作吗? 我试过使用 pass 但出现语法错误。
我有这个:
# 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]
我想忽略大于 1000 的项目。
谢谢,希望我已经说清楚了(这里的第一个问题)。
您需要首先 在外部for
表达式中过滤所需的值。
在其中,您选择 yes/no 回复:
['yes' if v == 1 else 'no'
for v in l if v in [1, 2]]
输出:
['yes', 'no']
我可能会在字典中对这种关系进行编码,以便您可以将其用于过滤和映射:
>>> l = [1, 2, 3, 4, 5]
>>> d = {1: 'yes', 2: 'no'}
>>> [d[v] for v in l if v in d]
['yes', 'no']