引用索引的列表中的返回元素 [英] return element in list refering to index

查看:47
本文介绍了引用索引的列表中的返回元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个单词列表:

Assuming I have a list of words:

l = ['example', 'to', 'a', 'list', 'of', 'words']

我得到一个索引i,比方说 10 .

And I get an index i, let's say 10.

我需要返回 l 中包含第i个字符的元素,

What I need is to return the element in l that contains the i-th char,

因此在10的示例中,由于第10个元素(从零开始)是单词 list 中的 l -我需要返回的是单词 list .

So in the example of 10, as the 10-th element (zero-based) is the l from the word list - what I need to return is the word list.

我一直在尝试一种简单的方法来实现此目的,但我没有发现任何优雅的方法.

Iv'e been trying to think of a simple way to do this, and I didn't find something elegant.

任何帮助将不胜感激!

推荐答案

from itertools import count

l = ['example', 'to', 'a', 'list', 'of', 'words']

c = count()
print(next(s for s in l for _, i in zip(s, c) if i == 10))

打印:

list


另一种解决方案(使用 bisect 模块):

from bisect import bisect
from itertools import accumulate

l = ['example', 'to', 'a', 'list', 'of', 'words']

lengths = [*accumulate(map(len, l))]
print(l[bisect(lengths, 10)])

这篇关于引用索引的列表中的返回元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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