📜  Python|检查元组和列表是否相同

📅  最后修改于: 2022-05-13 01:55:22.033000             🧑  作者: Mango

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

有时在Python中处理不同的数据时,我们可能会遇到在不同容器中保存数据的问题。在这种情况下,可能需要测试数据是否是相同的跨容器。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是执行此特定任务的蛮力方法。在此,我们只是迭代列表和元组以测试每个索引处的元素是否相似。

# Python3 code to demonstrate working of
# Check if tuple and list are identical
# Using loop
  
# Initializing list and tuple
test_list = ['gfg', 'is', 'best']
test_tup = ('gfg', 'is', 'best')
  
# printing original list and tuple 
print("The original list is : " + str(test_list))
print("The original tuple is : " + str(test_tup))
  
# Check if tuple and list are identical
# Using loop
res = True
for i in range(0, len(test_list)):
    if(test_list[i] != test_tup[i]):
        res = False
        break
  
# printing result
print("Are tuple and list identical ? : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best']
The original tuple is : ('gfg', 'is', 'best')
Are tuple and list identical ? : True

方法 #2:使用all() + zip()
也可以使用上述功能的组合在单行中执行此任务。在这里,我们只是使用zip()组合容器元素,并使用all()来测试相应索引处元素的相等性。

# Python3 code to demonstrate working of
# Check if tuple and list are identical
# Using all() + zip()
  
# Initializing list and tuple
test_list = ['gfg', 'is', 'best']
test_tup = ('gfg', 'is', 'best')
  
# printing original list and tuple 
print("The original list is : " + str(test_list))
print("The original tuple is : " + str(test_tup))
  
# Check if tuple and list are identical
# Using all() + zip()
res = all( [i == j for i, j in zip(test_list, test_tup)] )
  
# printing result
print("Are tuple and list identical ? : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best']
The original tuple is : ('gfg', 'is', 'best')
Are tuple and list identical ? : True