Python – 检查特定索引中的元素是否等于列表元素
当需要检查特定索引处的元素是否等于另一个元素列表时,可以使用简单的迭代和布尔值。
示例
以下是对此进行演示 -
my_list_1 = [69, 96, 23, 57, 13, 75, 13]
my_list_2 = [68, 21, 69, 23, 49, 35, 73]
print("The first list is : " )
print(my_list_1)
print("The first list after sorting is :")
my_list_1.sort()
print(my_list_1)
print("The second list is : " )
print(my_list_2)
print("The first list after sorting is :")
my_list_2.sort()
print(my_list_2)
check_list = [66, 89, 69]
print("The second list is : " )
print(check_list)
print("The check list after sorting is :")
check_list.sort()
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
if(my_result == True):
print("The elements of the list are equal to the elements in the check list")
else:
print("The elements of the list aren't equal to elements in the check list")输出
The first list is : [69, 96, 23, 57, 13, 75, 13] The first list after sorting is : [13, 13, 23, 57, 69, 75, 96] The second list is : [68, 21, 69, 23, 49, 35, 73] The first list after sorting is : [21, 23, 35, 49, 68, 69, 73] The second list is : [66, 89, 69] The check list after sorting is : [66, 69, 89] The elements of the list aren't equal to elements in the check list
说明
定义两个整数列表,并显示在控制台上。
对它们进行排序并显示在控制台上。
将布尔值赋值为 True。
使用“enumerate”迭代第一个列表。
比较特定索引处的元素,并检查该元素是否在第三个列表中找到。
如果没有找到,则布尔值将被赋值为“False”。
控制退出循环。
根据布尔值,在控制台上显示消息。
展示广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP