将一个列表中的变量插入/替换到另一列表中

时间:2019-07-26 21:41:57

标签: python random replace

list_x = ["a", "y", "l", "d", "e", "q", "g", "o", "i"]
list_y = ["e", "p", "z"]

我正在尝试将list_x中的随机项目替换为list_y中的项目,而不添加任何重复项。我研究了random.replace()random.choice(),但似乎无法弄清楚。

以下是我尝试获取的输出示例:

new_list_x = ["p", "y", "l", "d", "e", "z", "g", "o", "i"]

目标是插入/替换list_y中缺少的list_x中的所有字母,而不会超出list_x中的原始字母数。如果list_y中的一个字母已经在list_x中,请跳过它。所有list_y必须包含在list_x中。

6 个答案:

答案 0 :(得分:2)

这可以做到:

import random
list_x = ["a", "y", "l", "d", "e", "q", "g", "o", "i"]
list_y = ["e", "p", "z"]

# Create your list
new_list_x = list_x.copy()
for let in list_y:
    # Only add letters not already present (no duplicates)
    if let not in new_list_x:
        # This is needed to find a random letter to replace
        found = False
        while not found:
            num = random.choice(range(len(new_list_x)))
            # Only change letters that are not necessary 
            if new_list_x[num] not in list_y:
                found = True
                new_list_x[num] = let

print(new_list_x)

输出:

['z', 'y', 'l', 'd', 'e', 'q', 'g', 'o', 'p']

答案 1 :(得分:0)

new_list_x = list_x[:] . # makes a copy of list_x
max_index = len(new_list_x) - 1)
for letter in list_y:
    if letter not in list_x:
        new_list_x[random.randint(0, max_index] = letter

答案 2 :(得分:0)


    {
    "name_detect": [{
    "Bkav": "",
    "K7AntiVirus": "",
    "MicroWorld-eScan": "",
    "FireEye": "Generic.mg.2ab8e07333108029",
    "CAT-QuickHeal": "",
    "McAfee": "Artemis!2AB8E0733310",
    "ALYac": "",
    "Cylance": "Unsafe",
    "VIPRE": "",
    "Trustlook": "",
    "BitDefender": "",
    "K7GW": "",
    "Cybereason": "malicious.d53a10",
    "Arcabit": "",
    "Baidu": "",
    "Babable": "",
    "F-Prot": "W32/Trojan.SW.gen!Eldorado"
    }]
    }

答案 3 :(得分:0)

import random

list_x = ["a", "y", "l", "d", "e", "l", "g", "o", "i"]
list_y = ["e", "p", "z"]
for letter in list_y:
    if letter not in list_x:
        to_be_replaced = random.choice(list_x)
        index_to_be_replaced = list_x.index(to_be_replaced)
        list_x[index_to_be_replaced] = letter

答案 4 :(得分:0)

尝试一下:

import random

list_x = ["a", "y", "l", "d", "e", "l", "g", "o", "i"]
list_y = ["e", "p", "z"]

for item in list_y:
    if item in list_x:
        pass
    else:
        list_x[random.randint(0, len(list_x)-1)] = item
print(list_x)

答案 5 :(得分:0)

tolower()