简体   繁体   English

我如何通过列表理解中的最后一个 else

[英]How do i pass the last else in list comprehension

I'm trying make a if, elif list comprehension line... found this code in other question:我正在尝试制作一个 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']

My question is: Can I pass the last 'else' as a third action?我的问题是:我可以通过最后一个“其他”作为第三个动作吗? I've tried use pass but got a syntax error.我尝试过使用 pass 但出现语法错误。

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.我想忽略大于 1000 的项目。

Thanks, hope I had made my self clear(first question in here).谢谢,希望我已经说清楚了(这里的第一个问题)。

You need to first filter for the desired values, at the outer for expression.您需要首先在表达式的外部过滤for的值。 Within that, you choose your yes/no response:在其中,您选择是/否响应:

['yes' if v == 1 else 'no' 
       for v in l    if v in [1, 2]]

Output: Output:

['yes', 'no']

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM