使用python中的索引创建一个包含列表子集的新列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19252301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating a new list with subset of list using index in python
提问by user2783615
A list:
一个列表:
a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]
I want a list using a subset of a using a[0:2],a[4], a[6:]
,
我想要一个使用 using 的子集的列表a[0:2],a[4], a[6:]
,
that is I want a list ['a', 'b', 4, 6, 7, 8]
那是我想要一个清单 ['a', 'b', 4, 6, 7, 8]
采纳答案by rlms
Try new_list = a[0:2] + [a[4]] + a[6:]
.
试试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.
这也适用于其他序列,并且可能会更快。
Or you could do this:
或者你可以这样做:
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:])
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]
).
但请注意,如果列表中的某些元素本身就是列表,则会导致问题。要解决此问题,请使用以前的解决方案之一,或者替换a[4]
为a[4:5]
(或更一般地替换a[n]
为a[n:n+1]
)。
回答by Aurélien Ooms
The following definition might be more efficient than the first solution proposed
以下定义可能比提出的第一个解决方案更有效
def new_list_from_intervals(original_list, *intervals):
n = sum(j - i for i, j in intervals)
new_list = [None] * n
index = 0
for i, j in intervals :
for k in range(i, j) :
new_list[index] = original_list[k]
index += 1
return new_list
then you can use it like below
然后你可以像下面一样使用它
new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))
回答by G. Cohen
Suppose
认为
a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]
and the list of indexes is stored in
索引列表存储在
b= [0, 1, 2, 4, 6, 7, 8]
then a simple one-line solution will be
那么一个简单的单行解决方案将是
c = [a[i] for i in b]