Python – 检查列表元素的索引是否等于列表元素
当需要检查元素的索引是否等于列表中的元素时,使用简单的迭代和枚举属性。
示例
以下是同样的一个演示 −
my_list_1 = [12, 62, 19, 79, 58, 0, 99]
my_list_2 = [12, 74, 19, 54, 58, 0, 11]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
my_list_1.sort()
my_list_2.sort()
print("The first list after sorting is ")
print(my_list_1)
print("The second list after sorting is ")
print(my_list_2)
check_list = [9, 8, 2]
print("The check_list is :")
print(check_list)
my_result = True
for index, element in enumerate(my_list_1):
if my_list_1[index] != my_list_2[index] and element in check_list:
my_result = False
break
print("The result is :")
if(my_result == True):
print("The index elements is equal to the elements of the list")
else:
print("The index elements is not equal to the elements of the list")输出
The first list is : [12, 62, 19, 79, 58, 0, 99] The second list is : [12, 74, 19, 54, 58, 0, 11] The first list after sorting is [0, 12, 19, 58, 62, 79, 99] The second list after sorting is [0, 11, 12, 19, 54, 58, 74] The check_list is : [9, 8, 2] The result is : The index elements is equal to the elements of the list
说明
定义两个整数列表并在控制台上显示它们。
对它们进行排序并在控制台上显示。
定义另一个整数列表并在控制台上显示。
将一个值设为布尔值 True。
使用枚举遍历第一个列表,并比较两个相应列表的第一个两个元素的索引。
如果它们相等,并且此元素存在于整数列表中,则布尔值将被设为 False。
控件从循环中跳出。
根据布尔值,在控制台上显示相关消息。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP