在列表的特定范围内获取元素

时间:2019-05-28 15:00:47

标签: python list

我有一个Python列表,例如 window.addEventListener('load', () => { beautify.beautify(editor.session) }) 。另外,我还有另一个列表list = [1,2,3,4,5,6,7,8,9]。现在,我要执行以下操作:

list2 = ['a','b','c','d','e','f','g','h','j']

这应该产生idx = (list > 3) & (list < 7) list2 = list2[idx] 。当然,列表是不可能的。列表如何完成?

3 个答案:

答案 0 :(得分:6)

您可以使用zip

l1 = [1,2,3,4,5,6,7,8,9]
l2 = ['a','b','c','d','e','f','g','h','j']
result = [a for a, b in zip(l2, l1) if 3 < b < 7]

输出:

['d', 'e', 'f']

也要获取缩小列表:

result, reduced = map(list, zip(*[[a, b] for a, b in zip(l2, l1) if 3 < b < 7]))

输出:

['d', 'e', 'f'] #result
[4, 5, 6] #reduced

答案 1 :(得分:1)

尝试一下:

#Make sure all lists are numpy arrays.
import numpy as np
idx = np.where((list > 3) & (list < 7))
list2 = list2[idx]

答案 2 :(得分:0)

具有通过列表理解列表访问元素的选项:

res = [ list2[idx] for idx, e in enumerate(list1) if 7 > e > 3 ]
print(res) #=> ['d', 'e', 'f']


要从两个列表中获取元素:

[ [list2[idx], e] for idx, e in enumerate(list1) if 7 > e > 3 ]
#=> [['d', 4], ['e', 5], ['f', 6]]

然后转置:

res1, res2 = [ list(i) for i in zip(*[ [list2[idx], e] for idx, e in enumerate(list1) if 7 > e > 3 ]) ]
print (res1, res2 ) #=> ['d', 'e', 'f'] [4, 5, 6]