Random更换而不完全在Python中完全更改订单

A=[1,2,3,4,5,6,7]
B=[a,b,c,d,e,f,g,h,i,j,k,l]
C=[]

我希望在最多3个位置替换“B”的值的值,而无需更改其现有订单,并存储C的所有可能的变化。

out put应该如下

C=[(1,i,3,4,5,a,7),
   (1,a,b,4,a,6,7),
   (1,2,3,a,5,6,7),
   (1,b,a,4,5,6,),
   (c,2,3,4,5,6,7),
   ......]

请不要为其提出任何代码/逻辑/流。谢谢

I tried for loops but didnt help much.

I tried for loops:向我们展示你尝试过的东西。Selcuk
a = [1,2,3,4,5,6,7] b = ['a','b','c','d','e','f','g','h','i','j','k','l'] c = []我在a中:对于b中的j:a.remove(j)a.append(i)打印(a)CD100

回答 1

  1. 赞同 0

    Let的想法

    我们需要一个随机的替代品,即1-3。我们可以用random.randint生成此数字,然后random.sample从A和B获取一些随机元素切换。

    代码

    import random
    
    # Define variables
    A = [1,2,3,4,5,6,7]
    B = [a,b,c,d,e,f,g,h,i,j,k,l]
    C = []
    
    # Iterate how ever many times, i.e. 10
    for i in range(10):
        results = A
        swaps = random.randint(1, 3)
        swapA = random.sample(A, swaps)
        swapB = random.sample(B, swaps)
        
        # Group the swaps together, so we don't need to use an extra loop
        zipped = zip(swapA, swapB)
    
        # Replace numbers with letters
        for i in range(len(results)):
            # Check if this is the right place to swap
            for swap in zipped:
                if results[i] == swap[0]:
                    # Swap the two numbers!
                    results[i] = swap[1]
    
        # Add to results list
        C.append(results)
    
    # View results!
    print(C)
    

    Llry Llama
    当我运行这个时,我得到10个相同的列表。Mark
    它只是只改变一个价值,只有一个价值也是如此。cd100
    我得到:[['g', 2, 3, 4, 5, 6, 7], ['g', 2, 3, 4, 5, 6, 7], ['g', 2, 3, 4, 5, 6, 7], ['g', 2, 3, 4, 5, 6, 7], ['g', 2, 3, 4, 5, 6, 7], ['g', 2, 3, 4, 5, 6, 7], ['g', 2, 3, 4, 5, 6, 7], ['g', 2, 3, 4, 5, 6, 7], ['g', 2, 3, 4, 5, 6, 7], ['g', 2, 3, 4, 5, 6, 7]].我是错的吗?Mark