[英]How to determine that all the variables in my list are the same to each other in python 3
I am making this program where I am checking if the user gets a yahtzee or not and I want to check if all the variables are the same either 1,2,3,4,5,6 and I don't want to make 6 different lists. 我正在制作此程序,我正在检查用户是否得到yahtzee,并且我想检查所有变量是否都等于1,2,3,4,5,6,而我不想设为6不同的清单。 Is there any easy way to check? 有没有简单的检查方法?
Did you try something like the following already? 您是否已经尝试过以下方法? Ie essentially if they're all the same then they're also all the same as the first (index 0) element. 即从本质上讲,如果它们都相同,那么它们也与第一个(索引0)元素相同。
vals = [1, 1, 1, 1, 1]
same = all( [ v == vals[0] for v in vals] )
print(same)
outputs 输出
True
while 而
vals = [1, 2, 1, 2, 1]
same = all( [ v == vals[0] for v in vals] )
print(same)
outputs 输出
False
You could use a set
for this as follows: 您可以为此使用一个set
,如下所示:
vals = [1, 1, 1, 1, 1, 1]
if len(vals) == 6 and len(set(vals)) == 1:
print "yahtzee"
First check for the correct number of values (if required), then convert them to a set. 首先检查值的正确数量(如果需要),然后将它们转换为一组。 If they are all the same, the length of the set will be 1. 如果它们都相同,则集合的长度将为1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.