簡體   English   中英

迭代和組合列表中的元素

[英]Iterate and combine iteratively elements in a list

我有一個清單:

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

我想迭代並迭代地組合列表中的元素,例如第一個元素與第二個元素和 go 組合在一起。 我想要的最終 output 是:

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

我嘗試使用這種方式:

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

但我只得到這個結果:

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

知道我錯在哪里以及如何正確執行此操作嗎?

您的range值不正確,並且i未定義。 這是一個更簡單的循環:

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

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

Output:

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

您可以在使用range時修改startstop arguments :

li = ['a', 'b', 'c', 'd']
for i in range(1, len(li) + 1):
    output = li[:i]
    print(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