Python创建一个新列表,其中包含的元素不等于其他两个列表的相同索引的元素

时间:2019-02-06 13:32:06

标签: python list list-comprehension

我试图通过使用列表理解遍历其他两个列表并仅在列表中保留不等于其他两个列表的相同索引元素的整数来创建列表。

我有两个列表,其中包含10个从0到10的整数,例如:

list_1 = [0,3,2,5,7,2,3,5,9,2]

list_2 = [1,7,2,5,0,0,2,3,0,4]

我需要一个列表理解功能,以创建一个由10个整数组成的新列表,但是每个元素不能等于两个列表中相同的索引元素。

示例输出可能是:

list_3 = [4,4,9,6,3,1,5,7,6,1]

谢谢。

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

import random
random.seed(42)

list_1 = [0,3,2,5,7,2,3,5,9,2]
list_2 = [1,7,2,5,0,0,2,3,0,4]

n = 10
pool = set(range(n))

result = [random.sample(pool - set(t), 1)[0] for t in zip(list_1, list_2)]
print(result)

输出

[3, 0, 5, 3, 4, 4, 1, 1, 7, 0]

作为一种更快的替代方法,您可以执行以下操作:

result = [random.choice(list(pool - set(t))) for t in zip(list_1, list_2)]

答案 1 :(得分:0)

from random import randint

list_1 = [0,3,2,5,7,2,3,5,9,2]    
list_2 = [1,7,2,5,0,0,2,3,0,4]   
list_3 = []

for elem1 in list_1:
    for elem2 in list_2:
        x = randint(0, 9)
        if x != elem1 and x != elem2:
            list_3.append(x)
            break

print(list_3)

输出:

[6, 9, 8, 2, 6, 8, 4, 8, 0, 5]

编辑:

一个班轮:

from random import randint

list_1 = [0,3,2,5,7,2,3,5,9,2]    
list_2 = [1,7,2,5,0,0,2,3,0,4]
n = 10

print([randint(0, n) for i in list_1 if i in list_2])

输出:

[2, 9, 7, 8, 5, 10, 7, 1, 7]

答案 2 :(得分:0)

import random

def get_random(n, exclude):
    my_set = set(range(n+1))
    my_set.difference_update(set(exclude))
    return random.choice(list(my_set))

def get_random2(n, exclude):
    nums = list(range(n+1))
    while True:
        num =  random.choice(nums)
        if num not in exclude:
            return num

list1 = [0,3,2,5,7,2,3,5,9,2]
list2 = [1,7,2,5,0,0,2,3,0,4]

# print list with numbers between 0 and 10 inclusive
print([get_random(10, nums) for nums in zip(list1, list2)])
print([get_random2(10, nums) for nums in zip(list1, list2)])