繁体   English   中英

如何在 python 的中间创建一个包含另一个列表元素的列表?

[英]How can I create a list containing another list's elements in the middle in python?

我有三个清单。 两个是从函数返回的。 另一个列表list_c是在程序中由一些硬编码选项和一些变量以及这些列表的内容创建的。 此列表是要传递给另一个程序的 arguments 的列表,因此顺序很重要。 我需要list_alist_b中的每个项目位于某个 position 中的list_c中间。 list_alist_b的长度都是可变的。

list_a = some_function()
list_b = some_other_function()
list_c = ['some', 'stuff', list_a, 'more', list_b, variables]

基本上,我想要类似上面的东西,除了给出一个平面列表而不是嵌套列表。

我可以:

list_c = ['some', 'stuff']
list_c.extend(list_a)
list_c.append('more')
list_c.extend(list_b)
list_c.append(variables)

但这看起来有点笨拙,我很好奇是否有更优雅的方法来做到这一点。

这个怎么样? 您可以使用+附加/连接列表

['some', 'stuff'] + some_function() + ['more'] + some_other_function() + [variables]

最明显的方法是使用列表连接:

list_c = list_c + list_a + ['more'] + list_b + ['var1', 'var2']

对于它的价值, itertools.chain也有效。 我不知道为什么建议它被删除的答案。 如果作者取消删除它,我将从我的答案中删除它。

>>> list_a = ['some_function', 'results']
>>> list_b = ['some_other_function', 'results']
>>> variables = 'foo'
>>> list_c = list(itertools.chain(['some', 'stuff'], list_a, ['more'], list_b, [variables]))
>>> list_c
['some', 'stuff', 'some_function', 'results', 'more', 'some_other_function', 'results', 'foo']

另一个解决方案:

>>> lists_to_chain = [['some', 'stuff'], list_a, ['more'], list_b, [variables]]
>>> list_c = []
>>> for l in lists_to_chain:
...     list_c.extend(l)
... 
>>> list_c
['some', 'stuff', 'some_function', 'results', 'more', 'some_other_function', 'results', 'foo']
reduce(lambda x, y: x+y,
       [['some', 'stuff'], some_function(), ['more'], some_other_function(), variables])

比硬编码['some', 'stuff'] + some_function() + ['more'] + some_other_function() + [variables]更灵活,因为您可以在合并之前在运行时定义和操作包含列表。

暂无
暂无

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

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