简体   繁体   English

迭代和组合列表中的元素

[英]Iterate and combine iteratively elements in a list

I have a list:我有一个清单:

li = ['a','b','c','d']

I want to iterate and combine iteratively the elements in the list such as the first one is combined to the 2nd one and go on.我想迭代并迭代地组合列表中的元素,例如第一个元素与第二个元素和 go 组合在一起。 The final output I want is:我想要的最终 output 是:

['a'],['a','b'],['a','b','c'],['a','b','c','d']

I tried using this way:我尝试使用这种方式:

for i in range(0, len(li),i): 
    output = li[:i+i]
    print(output)

But I am getting only this result:但我只得到这个结果:

[]
['a', 'b', 'c', 'd']

Any idea where I am wrong and how to do this properly?知道我错在哪里以及如何正确执行此操作吗?

Your range values are incorrect, and i is undefined.您的range值不正确,并且i未定义。 This is a much simpler loop:这是一个更简单的循环:

li = ['a','b','c','d']

for i in range(len(li)):
    output = li[:i+1]
    print(i, output)

Output: Output:

0 ['a']
1 ['a', 'b']
2 ['a', 'b', 'c']
3 ['a', 'b', 'c', 'd']

You could modify the start and stop arguments in your use of range :您可以在使用range时修改startstop arguments :

li = ['a', 'b', 'c', 'd']
for i in range(1, len(li) + 1):
    output = li[:i]
    print(output)

Output: Output:

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']

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

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