英文:
How can I use list unpacking with condition in list?
问题
这是我正在尝试的:
[1,2,3 if False else *[6,5,7]]
这是我期望的:
[1,2,3,6,5,7]
如何在不展平列表的情况下使其工作 - 即 np.flatten([1,2,3 if False else [6,5,7]])
或类似的方法?
是否有一种方法可以解包列表中的 [6,5,7]
?非常感谢建议!
英文:
This is what I'm attempting
[1,2,3 if False else *[6,5,7]]
This is what I'm expecting
[1,2,3,6,5,7]
How could I get this to work without flattening the list - i.e. np.flatten([1,2,3 if False else [6,5,7]])
or similar
Is there an approach I can use to unpack [6,5,7]
inside my list? Advice much appreciated!
答案1
得分: 2
你可以根据条件解包[6, 5, 7]
或一个空列表:
condition = False
data = [1, 2, 3, *([] if condition else [6, 5, 7])]
# >>> [1, 2, 3, 6, 5, 7]
英文:
You could unpack [6, 5, 7]
or an empty list depending on a condition:
condition = False
data = [1, 2, 3, *([] if condition else [6, 5, 7])]
# >>> [1, 2, 3, 6, 5, 7]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论