[英]Can you randomly assign True or False to a set of variables through multiple assignment?
I would like to assign either True
or False
to the first variable and then have a second variable assignment be the opposite of the first one.我想将True
或False
分配给第一个变量,然后第二个变量赋值与第一个变量相反。 If the first variable is assigned a value of False
, then the second variable should become True
, and vice versa.如果第一个变量被赋值为False
,那么第二个变量应该变成True
,反之亦然。 My first thought was to do this with an if/else-statement, but it became apparent that there were too many assignments:我的第一个想法是用 if/else 语句来做这件事,但很明显有太多的分配:
Example 1:示例 1:
import random
if random.choice([True, False]):
player_turn = True
computer_turn = False
else:
player_turn = False
computer_turn = True
print(player_turn)
print(computer_turn)
I then decided to simplify the logic by leveraging the information from the first variable assignment:然后我决定通过利用第一个变量赋值的信息来简化逻辑:
Example 2:示例 2:
import random
player_turn = random.choice([True, False])
computer_turn = not player_turn
print(player_turn)
print(computer_turn)
Is it possible to reduce this down even further?是否有可能进一步减少这种情况? Perhaps, by utilizing multiple assignment to have this be just one line of code?也许,通过利用多重赋值让这只是一行代码?
Use random.sample
instead of random.choice
.使用random.sample
而不是random.choice
。 Since it picks values without replacement, the second element is necessarily whichever value wasn't chosen first.因为它选择没有替换的值,所以第二个元素必然是第一个没有选择的值。
player_turn, computer_turn = random.sample([True, False], 2)
Or, use an assignment expression (Python 3.8 or later) so that you can negate whichever value is return by random.choice
:或者,使用赋值表达式(Python 3.8 或更高版本),以便您可以否定random.choice
返回的任何值:
player_turn, computer_turn = (c := random.choice([True, False]), not c)
In practice, though, don't maintain two variables whose values have to be kept in sync.但实际上,不要维护两个值必须保持同步的变量。 One variable indicating whose turn it is suffices.一个变量,指示该轮到谁是足够了。
If you really must:如果你真的必须:
x, y = [i[1] if i[0]==0 else not i[1] for i in enumerate([random.choice([True, False])]*2)]
I guess you get the idea that the two lines are actually not that bad.我想你会认为这两行实际上并没有那么糟糕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.