python - Python列表定义-根据条件插入或不插入元素
问题描述
我可以定义一个列表:
c = some_condition # True or False
l = [
1, 2, # always
3 if c else 4
]
# l = [ 1, 2, 3 ] if c is True, [ 1, 2, 4 ] otherwise
但是,如果 c 为真,我如何定义一个列表,否则呢?[1,2,3]
[1,2]
l = [
1, 2,
3 if c # syntax error
]
l = [
1, 2,
3 if c else None # makes [1,2,None]
]
l = [
1, 2,
3 if c else [] # makes [1,2,[]]
]
# This is the best that I could do
l = (
[
1, 2,
]
+
([3] if c1 else []) # parentheses are mandatory
)
# Of course, I know I could
l = [1, 2]
if c:
l.append(3)
另外,我想知道当条件为真时如何插入多个元素:3, 4
而不是3
例如。
例如,在 Perl 中,我可以这样做:
@l = (
1, 2,
$c1 ? 3 : (), # empty list that shall be flattened in outer list
$c2 ? (4,5) : (6,7), # multiple elements
);
解决方案
c = some_condition # True or False
l = [1, 2] + [x for x in [3] if c]
print(l)
输出>>>
[1, 2, 3] # when c = True
[1, 2] # when c = False
您可以根据需要扩展它
l = [1, 2] + [x for x in [3] if c] + [x for x in [4] if not c]
输出>>>
[1, 2, 3] # when c = True
[1, 2, 4] # when c = False
推荐阅读
- php - chrome“net:加载资源失败:net::ERR_SPDY_PROTOCOL_ERROR”有什么问题?
- macos - launchctl 无法运行二进制文件并以代码 78 退出
- javascript - 意外的未定义从 Observable 作为订阅返回,其中需要对象
- php - 如何检查一组数字是否包含PHP中的某个数字?
- dart - 颤振错误:无法将参数类型“Future”分配给参数类型“Widget”
- javascript - 从反应到节点获取url参数
- c - 说明符 %[^s] 用于什么?
- node.js - 没有自定义授权者的 AWS lambda 基本身份验证
- c# - AspNetCore.Mvc.Core 版本不匹配
- authentication - sp 发起 saml sso 认证