借助带有条件的另一个列表从列表中提取值

时间:2019-05-28 08:02:46

标签: python

从列表中提取项目,并将其插入另一个列表项目之间

a = [4,8]
b = [1,2,3,4,5,6,7,8,9,0]

我想从b列表中提取值,这些值在a列表的4到8个值之间?

结果应该是

b = [5,6,7]

3 个答案:

答案 0 :(得分:2)

您可以使用内置的filter()方法。

a = [4, 8]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

# If you aren't sure that items in a is in correct order then use min max
c = list(filter(lambda x: min(a) < x < max(a), b))

或使用列表理解:

c = [x for x in b if min(a) < x < max(a)]

答案 1 :(得分:1)

In [8]: a = [4,8]

In [9]: b = [1,2,3,4,5,6,7,8,9,0]

In [10]: [ item for item in b if a[0] < item < a[1]]
Out[10]: [5, 6, 7]

答案 2 :(得分:0)

其他人则发布了依赖于整数的有序列表的答案。但是,如果您在无序列表上操作,其中值可以是任何类型,则此答案将在其他列表不起作用的情况下起作用。

result = b[b.index(a[0]) + 1 : b.index(a[1])]
In[2]: a = [1, "a"]; b = [0.229, "b", 1, [], "c", 5, "5", 2, "a"]
In[3]: b[b.index(a[0]) + 1 : b.index(a[1])]
Out[4]: [[], 'c', 5, '5', 2]