gpt4 book ai didi

python - 删除元素,然后迭代并组合列表中的元素python

转载 作者:行者123 更新时间:2023-12-02 02:22:02 25 4
gpt4 key购买 nike

假设我有一个这样的列表,其中包含 n 个元素:

myList = ['cr','cd','cs','sp','sd','op','ol','fs','th','ag','ng','rt','bp']

我想在迭代时每次删除列表中的一个元素,然后迭代地组合列表中的其他元素以获得如下输出:

# removing the first element, we would have:
['cd']
['cd', 'cs']
['cd', 'cs', 'sp']
['cd', 'cs', 'sp', 'sd']
['cd', 'cs', 'sp', 'sd', 'op']
['cd', 'cs', 'sp', 'sd', 'op', 'ol']
['cd', 'cs', 'sp', 'sd', 'op', 'ol', 'fs']
['cd', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th']
['cd', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag']
['cd', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag', 'ng']
['cd', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag', 'ng', 'rt']
['cd', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag', 'ng', 'rt', 'bp']

# Then removing the second element, we would have:

['cr']
['cr', 'cs']
['cr', 'cs', 'sp']
['cr', 'cs', 'sp', 'sd']
['cr', 'cs', 'sp', 'sd', 'op']
['cr', 'cs', 'sp', 'sd', 'op', 'ol']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag', 'ng']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag', 'ng', 'rt']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag', 'ng', 'rt', 'bp']

# Removing ith element:
........

我尝试过这样每次手动删除一个元素:

# 2nd element is removed
myList = ['cr','cs','sp','sd','op','ol','fs','th','ag','ng','rt','bp']
for i in range(1, len(myList) + 1):
input_f = myList[:i]
print(input_f)

并得到这个结果:

['cr']
['cr', 'cs']
['cr', 'cs', 'sp']
['cr', 'cs', 'sp', 'sd']
['cr', 'cs', 'sp', 'sd', 'op']
['cr', 'cs', 'sp', 'sd', 'op', 'ol']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag', 'ng']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag', 'ng', 'rt']
['cr', 'cs', 'sp', 'sd', 'op', 'ol', 'fs', 'th', 'ag', 'ng', 'rt', 'bp']

这让我更近了一步,但我不知道如何自动处理其余的事情。任何想法将不胜感激。

最佳答案

myList = ['a','b','c']

for index,elem in enumerate(myList):
myList.pop(index)
print(myList)
myList.insert(index,elem)

关于python - 删除元素,然后迭代并组合列表中的元素python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66276616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com