Python列表索引多个范围

时间:2015-04-21 20:15:27

标签: python list

很抱歉,如果已经有人询问过,我无法在任何地方找到它。基本上我如何在Python中的列表中获得2个单独的范围。

如果我想要列表中的第1,第2,第5和第6个元素,我知道我可以这样做,

l = range(0,15)
l[1:3]+l[5:7]

但这假设l很容易写。但是我正在使用BeautifulSoup4从网页中删除一些东西,所以我使用的是soup.find_all(它给了我一个列表),所以我不能简单地写出2个列表,然后将它们连接起来。

我想要一个类似

的答案
l = range(0,15)
l[1:3,5:7]

(但当然没有错误):)

4 个答案:

答案 0 :(得分:3)

这个可能就是你想要的。 itemgetter创建一个检索列出的索引的函数:

>>> import operator
>>> snip = operator.itemgetter(1,2,5,6)
>>> snip(range(15))
(1, 2, 5, 6)
>>> snip('abcdefg')
('b', 'c', 'f', 'g')
>>> snip([1,2,3,4,5,6,7,8])
(2, 3, 6, 7)

答案 1 :(得分:2)

我会用函数执行此操作:

def multi_range(l, *args):
    output = []
    for indices in args:
        output += l[indices[0]:indices[1]]
    return output

所以第一个参数是列表,其余的参数是带有你想要拉的索引的元组。使用长列表名称可以正常工作:

long_list_name = range(0, 15)
print multi_range(long_list_name, (1, 3), (5, 7))
>>> [1, 2, 5, 6]

答案 2 :(得分:1)

l = range(0, 15)
print([l[i] for i in [1,2, 5,6]])

不确定为什么你认为l[1:3]+l[5:7] hard ,find_all会像其他任何一样返回一个普通的python列表。

或使用地图:

l = range(0, 15)
print(list(map(l.__getitem__,(1,2,5,6))))

答案 3 :(得分:-1)

这样可以吗?

indices = [1, 2, 5, 6]
selected = [l[i] for i in indices]