这是我的代码:
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()
函数:if all(len(tup) == 3 for tup in x):
print(True)
else:
print(False)
这是一个简短的命令:
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)
另一种方法是使用namedTuple
。您可以使用它来创建点列表,而无需检查点列表。doc。
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
这将返回与每个元组对应的列表:
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
中使用布尔值即可。 - Eric Duminil