简体   繁体   English

如何确定我列表中的所有变量在python 3中彼此相同

[英]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.

相关问题 如何在python中将列表中的所有元素彼此相乘? - How to multiply all elements in a list with each other in python? 如何使变量在python中彼此相减 - How to make to variables to subtracted each other in python 如何在python中仅使用最后一个字符创建互不相同的变量列表 - How to create a list of variables that differ from each other with only last character in python 确定所有项目在Python中是否都相同 - Determine if all Items are same in Python 如何将一列的每一行与 python 中大型数据集的同一列的所有其他行进行比较? - How to compare each row of a column to all the other row of the same column of a large dataset in python? 如何在不删除python中的元素的情况下更改彼此相邻的列表中相同元素的出现? - How to change occurrence of the same element in a list next to each other without deleting the element in python? 确定Python列表是否相同95%? - Determine if a Python list is 95% the same? 如何为两个相等的集合变量的所有组合设置条件 - how to put a condition for all combinations of 2 of a set variables equaling each other 在Python中创建动态大小的lambdas列表,但它们彼此完全相同 - Creating list of lambdas in Python of dynamic size, but they all are identical to each other Python - 从 same.py 文件中的所有变量创建列表 - Python - Create list out of all variables in same .py file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM