![](/img/trans.png)
[英]Creating a new list based on matching elements of two nested lists in Python?
[英]Python creating a new list that contains elements not equal to elements of the same index of two other lists
我正在嘗試通過使用列表理解遍歷其他兩個列表並僅在列表中保留不等於其他兩個列表的相同索引元素的整數來創建列表。
我有兩個列表,其中包含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]
提前致謝。
您可以執行以下操作:
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)]
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]
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)])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.