在定义列表时,有没有办法有条件地将项添加到列表中? 这就是我的意思:
l = [
Obj(1),
Obj(2),
Separator() if USE_SEPARATORS,
Obj(3),
Obj(4),
Obj(5),
Separator() if USE_SEPARATORS,
Obj(6)
]
显然上面的代码不起作用,但是有类似的方法吗?
目前我有
l = [item for item in (
Obj(1),
Obj(2),
Separator() if USE_SEPARATORS,
Obj(3),
Obj(4),
Obj(5),
Separator() if USE_SEPARATORS,
Obj(6)
) if not isinstance(item, Separator) or USE_SEPARATORS]
但是我想知道是否还有其他方法不需要在列表中循环,因为它们可以是10000个项目长度,并且当我执行代码时服务器停止四分之一秒左右。 这是第一人称射击游戏,所以四分之一秒可能会对死亡或生活的人产生影响。
答案 0 :(得分:4)
我之后只需插入 ;列表毕竟是可变的:
l = [
HeadObj(1),
HeadObj(2),
BodyObj(1),
BodyObj(2),
BodyObj(3),
FooterObj(1)
]
if USE_SEPARATORS:
l.insert(2, Separator())
l.insert(6, Separator())
答案 1 :(得分:0)
如果不需要,我会添加分隔符并将其删除:
l = [
Obj(1),
Obj(2),
Separator(),
Obj(3),
Obj(4),
Obj(5),
Separator(),
Obj(6)]
if not USE_SEPARATORS:
l = [object for object in l if not isinstance(object, Separator)]
答案 2 :(得分:0)
另一种方法是使用splat / unpacking运算符:
possible_separator = (Separator(),) if USE_SEPARATORS else ()
l = [
Obj(1),
Obj(2),
*possible_separator,
Obj(3),
Obj(4),
Obj(5),
*possible_separator,
Obj(6)
]