简体   繁体   English

Python - 枚举后创建一个包含 n 个索引的列表

[英]Python - Create a list of n index after enumeration

words=["I","like","chocolate","I","like","strawberry"]

for i,l in enumerate(words,start=1):
    print(i)

This a simple code and what I would like to have the following output (i/o the one from the presented code):这是一个简单的代码,我希望有以下 output(i/o 来自所提供代码的代码):

[[1,2,3],[4,5,6]] [[1,2,3],[4,5,6]]

Meaning, I want a list composed of two sublists of n=3 with the indexes that came from the enumerate.意思是,我想要一个由 n=3 的两个子列表组成的列表,其中的索引来自枚举。

Is this possible?这可能吗? I believe it might be easy, but even after searching for an answer, nothing was good enough to provide me with what I need.我相信这可能很容易,但即使在寻找答案之后,也没有什么能满足我的需要。 Thanks in advance提前致谢

Taking a stab at it and hopefully the simple solution works for you.尝试一下,希望这个简单的解决方案对您有用。 Keep 2 lists one for enumerating and one for keeping the results.保留 2 个列表,一个用于枚举,一个用于保存结果。 Keep checking length of one list and when it reaches the threshold append to results.继续检查一个列表的长度,并在它达到阈值 append 时得出结果。

words=["I","like","chocolate","I","like","strawberry"]
l=[]
result=[]
for i,w in enumerate(words,start=1):
    l.append(i)
    if len(l) == 3:
        result.append(l)
        l = []
if l:
    result.append(l) # [[1, 2, 3], [4, 5, 6]]
print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM