Select 集合中的一个变量基于避免另一个变量
Select a variable in a collection based on avoiding another
我有两个变量的集合
a = 2
b = 3
collection = [a, b]
我随机选择其中一个作为我的第一个变量:
first_variable = random.choice(collection)
以后想select另一个变量存入other_variable
。
怎么才能只参考first_variable
和collection
呢?
other_variable = 类似于“collection
中的变量不是 first_variable
”
备注:该集合将始终只包含两个元素。
谢谢。
直截了当:
a = 2
b = 3
collection = [a, b]
import random
first_variable = random.choice(collection)
other_variable = [item for item in collection if item != first_variable][0]
print(other_variable)
注意:如果 a == b
这显然会失败(它会产生 IndexError
)。
只需 shuffle
您的集合并使用索引来引用您的 first
和 other
变量:
>>> import random
>>> collection = [2, 3]
>>> random.shuffle(collection)
>>> print(f'first={collection[0]}, other={collection[1]}')
first=3, other=2
我有两个变量的集合
a = 2
b = 3
collection = [a, b]
我随机选择其中一个作为我的第一个变量:
first_variable = random.choice(collection)
以后想select另一个变量存入other_variable
。
怎么才能只参考first_variable
和collection
呢?
other_variable = 类似于“collection
中的变量不是 first_variable
”
备注:该集合将始终只包含两个元素。 谢谢。
直截了当:
a = 2
b = 3
collection = [a, b]
import random
first_variable = random.choice(collection)
other_variable = [item for item in collection if item != first_variable][0]
print(other_variable)
注意:如果 a == b
这显然会失败(它会产生 IndexError
)。
只需 shuffle
您的集合并使用索引来引用您的 first
和 other
变量:
>>> import random
>>> collection = [2, 3]
>>> random.shuffle(collection)
>>> print(f'first={collection[0]}, other={collection[1]}')
first=3, other=2