[英]Python: If an item in list A exists in list B then output a random result that is not the same
Basically, I have 2 lists like this:基本上,我有 2 个这样的列表:
list_A = [A,B,C,D,E]
list_B = [B,C,A,E,D]
and I want to output one random element from each list:我想 output 每个列表中的一个随机元素:
Example Output:示例 Output:
From list_A: "A"
From list_B: "D"
How do I write code to avoid giving the same element?如何编写代码以避免给出相同的元素?
Example of wrong output:错误 output 示例:
From list_A: "A"
From list_B: "A"
This is what I tried but don't know how to continue:这是我尝试过但不知道如何继续的方法:
for a in list_A:
for b in list_B:
if a in list_B:
print(...)
You can do this:你可以这样做:
import random
list_A = ['A', 'B', 'C', 'D', 'E']
list_B = ['B', 'C', 'A', 'E', 'D']
a = random.choice(list_A)
b = random.choice(list_B)
while a == b:
b = random.choice(list_B)
print('From list_A: ' + a)
print('From list_B: ' + b)
I am sure there are better ways of doing this, but I think this is the simplest one to understand:我确信有更好的方法可以做到这一点,但我认为这是最容易理解的方法:
import random
list_a = ["A", "B", "C", "D", "E"]
list_b = ["A", "F", "G", "H", "I"]
rand_a = random.choice(list_a)
rand_b = random.choice(list_b)
while(rand_a == rand_b):
rand_b = random.choice(list_b)
print(rand_a)
print(rand_b)
From my point of view the best way of doing it is as follows:从我的角度来看,最好的方法如下:
import random
from itertools import permutations
list_AB = ['A','B','C','D','E']
pairsAB = list(permutations(list_AB, 2))
print( random.choice(pairsAB) )
The above solution is valid in the above case of question as lists A and B have same elements so random choice from one is equivalent to random choice from the other.上述解决方案在上述问题的情况下是有效的,因为列表 A 和 B 具有相同的元素,因此从一个中随机选择等同于从另一个中随机选择。 This allows to create all possible pairs of results and then choose random from them.
这允许创建所有可能的结果对,然后从中随机选择。
Another sub-optimal approach to the same requirement is using sets:满足相同要求的另一种次优方法是使用集合:
list_A = ['A','B','C','D','E']
list_B = ['B','C','A','E','D']
set_B = set(list_B)
import random
choice_A = random.choice(list_A)
choice_B = random.choice(list(set_B-set(choice_A)))
print( choice_A, choice_B )
The approach above does not unnecessary loop choosing always only twice and doesn't also need any if
statement or or ==
comparison.上面的方法不需要循环选择总是只有两次,也不需要任何
if
语句或 or ==
比较。 There is a good reason why Python provides sets along with lists and dictionaries. Python 提供集合以及列表和字典是有充分理由的。
You can do like this,你可以这样做,
list_A = ['A', 'B', 'C', 'D', 'E']
list_B = ['B', 'C', 'A', 'E', 'D']
a = random.choice(list_A)
b = random.choice([i for i in list_B if i != a])
print(f'From list_A: {a}')
print(f'From list_B: {b}')
# Result
From list_A:A
From list_B:C
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.