如何解决返回列表中引用索引
假设我有一个单词列表:
l = ['example','to','a','list','of','words']
我得到一个索引i,比方说10
。
我需要返回l
中包含第i个字符的元素,
因此在10的示例中,第10个元素(从零开始)是单词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和海象运算符来跟踪您的计数。基本上保持从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'
,
var emailResult = result.data.userData;
console.log('Successfully fetched user data:',emailResult);
打印:
result.data.text
另一种解决方案(使用bisect
模块)
from itertools import count
l = ['example','words']
c = count()
print(next(s for s in l for _,i in zip(s,c) if i == 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很简单...
In [1]: l = ['example','words']
In [2]: s = "".join(l)
In [3]: s
Out[3]: 'exampletoalistofwords'
In [4]: s[10]
Out[4]: 'l'
我相信,即使在1行代码中,它仍然是可读的(pythonic)
"".join( ['example','words'])[10]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。