Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python——验证列表中的元组具有相同的长度_Python_Arrays_List_Loops_For Loop - Fatal编程技术网

Python——验证列表中的元组具有相同的长度

Python——验证列表中的元组具有相同的长度,python,arrays,list,loops,for-loop,Python,Arrays,List,Loops,For Loop,这是我的密码: x = [(1, 2, 3), (4, 5, 6)] for tup in x: if len(tup) == 3: print(True) else: print(False) 我想验证列表中具有相同长度3的元组。如果列表中的任何元组的值大于或小于3,我想打印单个输出False。如果所有元组都有3个值,那么它应该打印单个输出True 目前,for循环产生多个输出。如何调整for循环?您可以使用all(): 另一种方法是

这是我的密码:

x = [(1, 2, 3), (4, 5, 6)]

for tup in x:
     if len(tup) == 3:
        print(True) 
     else:
        print(False) 
我想验证列表中具有相同长度3的元组。如果列表中的任何元组的值大于或小于3,我想打印单个输出
False
。如果所有元组都有3个值,那么它应该打印单个输出
True

目前,for循环产生多个输出。如何调整for循环?

您可以使用
all()


另一种方法是使用
namedTuple
。您可以使用此创建点列表,而不是检查点列表

这是一条单行线:

print(all(len(t) == 3 for t in x))

此问题的一个方便解决方案是使用
break
关键字和循环操作,如下所示:

x = [(1, 2, 3), (4, 5, 6)]
tupleCheck = True
for tup in x:
    if len(tup) != 3:
       tupleCheck = False # Here, the program realizes that a tuple does not have a length of 3...
       break # and aborts.
print(tupleCheck)

虽然有些冗余,但此解决方案可读性很强。

这给出了对应于每个元组的列表:

x=[(1,2,3),(1,2,2)]
d=[len(a)==3 for a in x]
p=True
for i in d:
    p= i and p
print p

你会收到裁员部的警告!切勿使用
if/else
仅打印True或False。直接从
all
;)使用布尔值我同意,但我可能错误地假设OP有两个逻辑分支,只是为MCVE打印—但他确实明确要求打印。我会更新,但是@DanilSperansky包含了一行代码。与使用列表理解和all()相比,代码太多,速度也慢了@Y0da我尝试使用OP的“调整for循环”的想法,而不是完全破坏所有内容并制作一行代码。但是,如果没有提到前面提到的“调整”,那么使用list comp+all()是更好的解决方案。我得到了动机,但在我看来,这与list comp+all()相比是不可读的,后者更像python。这种回答(@danil speransky)有助于每个人变得更像Python,编写更好的代码=)我很确定,如果我有
all
版本,我就永远不会使用
set
版本。具体地说,
all
更清晰,它能够在发现错误长度的元组时立即短路。<代码>设置<代码>版本''在决定之前总是要查看每一元组。@ JoelLawZiYang考虑接受其中一个答案,实际上非常喜欢这种方法。最好在创建数据结构时强制设置其格式,而不是在使用数据结构的每一点都检查它。
x = [(1, 2, 3), (4, 5, 6)]
tupleCheck = True
for tup in x:
    if len(tup) != 3:
       tupleCheck = False # Here, the program realizes that a tuple does not have a length of 3...
       break # and aborts.
print(tupleCheck)
x=[(1,2,3),(1,2,2)]
d=[len(a)==3 for a in x]
p=True
for i in d:
    p= i and p
print p