2024-04-26 11:17:16 发布
网友
假设我有一个单词列表:
l = ['example', 'to', 'a', 'list', 'of', 'words']
我得到一个索引I,比如说10
10
我需要返回l中包含第I个字符的元素
l
所以在10的例子中,因为第10个元素(基于零)是单词list中的l-我需要返回的是单词list
list
我一直在想一个简单的方法来做这件事,但我没有找到优雅的东西
任何帮助都将不胜感激
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,这就是字符串:
i
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))
印刷品:
另一种解决方案(使用^{}模块):
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)])
如果你想在函数中使用它
您也可以使用next和walrus操作符来跟踪您的计数。基本上,从
i
中减去每个字符串的长度,然后一旦i小于0,这就是字符串:结果:
印刷品:
另一种解决方案(使用^{} 模块):
相关问题 更多 >
编程相关推荐