在python中访问列表或字符串的非连续元素 [英] Accessing non-consecutive elements of a list or string in python

查看:167
本文介绍了在python中访问列表或字符串的非连续元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,这在官方上是不可能的,但是是否存在通过切片来访问列表中任意非顺序元素的技巧"?

As far as I can tell, this is not officially not possible, but is there a "trick" to access arbitrary non-sequential elements of a list by slicing?

例如:

>>> L = range(0,101,10)
>>> L
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

现在我想能够做

a,b = L[2,5]

,这样a == 20b == 50

除了两条语句之外,一种方式是愚蠢的:

One way besides two statements would be something silly like:

a,b = L[2:6:3][:2]

但这根本无法扩展到不规则的间隔.

But that doesn't scale at all to irregular intervals.

也许使用我想要的索引来理解列表?

Maybe with list comprehension using the indices I want?

[L[x] for x in [2,5]]

我很想知道针对此常见问题的建议.

I would love to know what is recommended for this common problem.

推荐答案

像这样吗?

def select(lst, *indices):
    return (lst[i] for i in indices)

用法:

>>> def select(lst, *indices):
...     return (lst[i] for i in indices)
...
>>> L = range(0,101,10)
>>> a, b = select(L, 2, 5)
>>> a, b
(20, 50)

该函数的工作方式是返回一个生成器对象,该对象可以类似地进行迭代到任何种类的Python序列.

The way the function works is by returning a generator object which can be iterated over similarly to any kind of Python sequence.

正如@justhalf在注释中指出的那样,可以通过定义函数参数的方式来更改您的调用语法.

As @justhalf noted in the comments, your call syntax can be changed by the way you define the function parameters.

def select(lst, indices):
    return (lst[i] for i in indices)

然后您可以使用以下命令调用该函数:

And then you could call the function with:

select(L, [2, 5])

或您选择的任何列表.

更新:我现在建议改为使用operator.itemgetter,除非您确实需要生成器的惰性评估功能.参见 John Y的答案.

Update: I now recommend using operator.itemgetter instead unless you really need the lazy evaluation feature of generators. See John Y's answer.

这篇关于在python中访问列表或字符串的非连续元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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