Python列表索引多个范围 [英] Python List indexing multiple ranges

查看:44
本文介绍了Python列表索引多个范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果已经问过这个问题,我在任何地方都找不到.基本上,我如何在Python列表中获得2个单独的范围.

Sorry if this has already been asked, I couldn't find it anywhere. Basically how do I get 2 separate ranges within a list in Python.

如果我想要列表的第一,第二,第五和第六个元素,我知道我可以做到,

If I want the 1st, 2nd, 5th and 6th elements of a list I know I can do this,

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

但是,这假设l易于编写.但是,我使用BeautifulSoup4从网页上抓取了一些内容,所以我使用了soup.find_all(它为我提供了一个列表),所以我不能简单地写出2个列表,然后将它们连接起来.

but this assumes that l is easy to write. However I am scrapping something from a webpage using BeautifulSoup4, so I'm using soup.find_all (which gives me a list), so I can't simply write out 2 lists, l and concatenate them.

我想要一个类似

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

(但当然没有错误):)

(but of course without the error) :)

推荐答案

可能是您想要的. itemgetter 创建一个函数来检索列出的索引:

This might be what you want. itemgetter creates a function that retrieves the listed indices:

>>> 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)

这篇关于Python列表索引多个范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆