检查元组和列表在 Python 中是否相同


当需要检查元组和列表是否相同时,可以使用一个简单的循环,即它们包含相同的元素。

可以使用列表来存储异构值(即任何数据类型的数据,如整数、浮点数、字符串等)。

以下是对此进行演示 −

示例

实时演示

my_tuple_1 = ('Hi' , 'there', 'Will')
my_list = ['How' ,'are' ,'you']

print("The tuple is : ")
print(my_tuple_1)
print("The list is : ")
print(my_list)

my_result = True
for i in range(0, len(my_list)):
   if(my_list[i] != my_tuple_1[i]):
      my_result = False
      break
print("Are the tuple and list identical ? ")
print(my_result)

输出

The tuple is :
('Hi', 'there', 'Will')
The list is :
['How', 'are', 'you']
Are the tuple and list identical ?
False

说明

  • 元组和列表在控制台上定义并显示。
  • 将“True”值分配给一个变量。
  • 将遍历列表,并比较列表和元组中的每个元素。
  • 如果不是相同的,则先前被分配“True”的变量将被分配“False”值。
  • 它将跳出循环。
  • 最终结果是存储在变量中的布尔值。
  • 它显示在控制台上

更新于: 2021-03-12

253 浏览量

职业生涯从这里开始

完成课程获得认证

开始学习
广告
© . All rights reserved.