如何在列表上重复操作

时间:2018-04-05 10:16:51

标签: python python-3.x for-loop

我想要一个4个字母的列表,然后我想随机选择它的两个元素,将它们合并在一起,并将它作为新元素添加到原始列表中。这样我就制作了一个新列表。现在我想从新列表中重复相同的过程,这意味着从新列表中取两个元素将它们随机合并在一起并再次创建一个新列表。到目前为止,我做了第一步:

import random
num = 2
aList = ['A','B','C','D']
newList = []
newList+=random.sample(aList, num)
L = [''.join(newList[0:2])]+aList
print(L)

我想知道如何再重复这个程序5次。

4 个答案:

答案 0 :(得分:2)

试试这个

import random
aList = ['A','B','C','D']
for i in range(5): aList.append(''.join(random.sample(aList, num)))
print(aList)

答案 1 :(得分:1)

我可以创建一个方法:

import random
num = 2
aList = ['A','B','C','D']
def randomizeList(list):
    newList = []
    newList+=random.sample(list, num)
    L = [''.join(newList[0:2])]+list
    return L

现在你可以根据需要多次调用此方法:

list = randomizeList(randomizeList(randomizeList(randomizeList(aList))))

list1 = randomizeList(aList)
list2 = randomizeList(list1)
list3 = randomizeList(list2)

和......

答案 2 :(得分:0)

创建一个功能:

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']

答案 3 :(得分:0)

试试这个

     import random
     def randomoperation():
         num = 2
         aList = ['A', 'B', 'C', 'D']
         newList = []
         newList += random.sample(aList, num)
         L = [''.join(newList[0:2])]+aList
         return L
     for i in range(5):
         print randomoperation()