假设我有一个单词列表:
l = ['example', 'to', 'a', 'list', 'of', 'words']
我得到一个索引I,比方说10
。
我需要的是返回l
中包含第I个字符的元素
所以在10的例子中,由于第10个元素(基于零(是单词list
中的l
,所以我需要返回的是单词list
。
Iv一直在想一个简单的方法来做这件事,但我没有找到优雅的东西。
任何帮助都将不胜感激!
i = 10
for word in l:
i -= len(word)
if i < 0:
break
# the value of word is 'list'
如果你想把它放在功能中
def at_index(l, i):
for word in l:
i -= len(word)
if i < 0:
return word
return None
您也可以使用next和walrus操作符来跟踪您的计数。基本上,从i
中减去每个字符串的长度,然后一旦i小于0,就是字符串:
l = ['example', 'to', 'a', 'list', 'of', 'words']
i = 10
result = next(s for s in l if (i:= i-len(s)) < 0)
结果:
'list'
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)])
类似的东西?
ind = 10
ll = 0
for item in l:
ll+=len(item)
if ll>=ind+1:
print(item)
break
为每个字母重复每个单词,然后只选择第i个单词:
[s for s in l for _ in s][i]
或者更有效地使用生成器和itertools.islice
:
next(islice((s for s in l for _ in s), i, None))
我弄错了。。。@-----Keeo it simple。。。
In [1]: l = ['example', 'to', 'a', 'list', 'of', 'words']
In [2]: s = "".join(l)
In [3]: s
Out[3]: 'exampletoalistofwords'
In [4]: s[10]
Out[4]: 'l'
我相信,即使在一行代码中,它仍然是可读的(Python(
"".join( ['example', 'to', 'a', 'list', 'of', 'words'])[10]