如何在列表上重复操作 [英] How to repeat an operation on a list
本文介绍了如何在列表上重复操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个由4个字母组成的列表,然后我想随机选择其中的两个元素,将它们合并在一起,并将其作为新元素添加到原始列表中.这样,我就列出了新清单.现在,我想从新列表中重复相同的过程,这意味着从新列表中获取两个元素,将它们随机合并在一起,然后再次创建一个新列表.到目前为止,我已经执行了第一步:
I want to have a list of 4-letters, then I want to pick two elements of it randomly, merge them together, and add it as a new element to the original list. This way I make a new list. Now I want to repeat the same procedure from the new list, meaning taking two elements from the new list randomly merge them together and make a new list again. So far I did the first step:
import random
num = 2
aList = ['A','B','C','D']
newList = []
newList+=random.sample(aList, num)
L = [''.join(newList[0:2])]+aList
print(L)
我想知道如何重复该过程再说5次.
I wonder how to repeat the procedure say 5 more times.
推荐答案
通过创建函数:
import random
def randMerge(l:list, count:int) -> list:
"""Returns the input list expanded by a joined element consisting of
count elements from itself (no repeats allowed)"""
return l + [''.join(random.sample(l,k=count))]
并反复调用:
num = 2
aList = ['A','B','C','D']
newList = aList[:]
for _ in range(6):
print(newList)
newList = randMerge(newList,num)
print(newList)
输出:
['A', 'B', 'C', 'D']
['A', 'B', 'C', 'D', 'DC']
['A', 'B', 'C', 'D', 'DC', 'ADC']
['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD']
['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD', 'CDA']
['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD', 'CDA', 'CDC']
['A', 'B', 'C', 'D', 'DC', 'ADC', 'CD', 'CDA', 'CDC', 'ADCCDC']
这篇关于如何在列表上重复操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文