Python - 测试元组列表是否包含一个元素
当需要测试元组列表是否包含一个元素时,需要使用一个标志值和一个简单的迭代。
示例
以下是对其进行演示
my_list = [(72, 72, 72), (72, 72), (72, 72)]
print("The list is :")
print(my_list)
my_result = True
for sub in my_list:
flag = True
for element in sub:
if element != my_list[0][0]:
flag = False
break
if not flag:
my_result = False
break
if(flag == True):
print("The tuple contains a single element")
else:
print("The tuple doesn't contain a single element")输出
The list is : [(72, 72, 72), (72, 72), (72, 72)] The tuple contains a single element
解释
定义了一个列表元组并将其显示在控制台上。
将一个变量赋值为“True”。
迭代该列表,并将一个值标记为“True”。
如果列表的元素不等于列表的第一个元素,则将该值标记为“False”。
否则,将变量更改为“False”。
跳出循环。
在方法外部,如果标记值是“True”,则表示该列表仅包含一个元素。
在控制台上显示相关消息。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP