使用python中的索引创建包含list子集的新列表 [英] creating a new list with subset of list using index in python
本文介绍了使用python中的索引创建包含list子集的新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
列表:
a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]
我想要一个使用<$的子集的列表c $ c> a [0:2],a [4],a [6:] ,
我想要一个清单 ['a','b',4,6,7,8]
推荐答案
尝试 new_list = a [0:2] + [a [4]] + a [6:]
。
或更一般地说,这样的事情:
Or more generally, something like this:
from itertools import chain
new_list = list(chain(a[0:2], [a[4]], a[6:]))
这也适用于其他序列,并且可能更快。
This works with other sequences as well, and is likely to be faster.
或者你可以这样做:
def chain_elements_or_slices(*elements_or_slices):
new_list = []
for i in elements_or_slices:
if isinstance(i, list):
new_list.extend(i)
else:
new_list.append(i)
return new_list
new_list = chain_elements_or_slices(a[0:2], a[4], a[6:])
但要注意,如果列表中的某些元素本身就是列表,这会导致问题。
要解决此问题,请使用以前的解决方案之一,或者将 a [4]
替换为 a [4:5]
(或者更通常 a [n]
, a [n:n + 1]
)。
But beware, this would lead to problems if some of the elements in your list were themselves lists.
To solve this, either use one of the previous solutions, or replace a[4]
with a[4:5]
(or more generally a[n]
with a[n:n+1]
).
这篇关于使用python中的索引创建包含list子集的新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文