可以使用嵌套循环来比较列表中的所有元素。具体示例代码如下所示:
list_of_elems = [1, 5, 2, 4, 3]
for i in range(len(list_of_elems)):
for j in range(i+1, len(list_of_elems)):
if list_of_elems[i] < list_of_elems[j]:
print(f"{list_of_elems[i]} is less than {list_of_elems[j]}")
elif list_of_elems[i] > list_of_elems[j]:
print(f"{list_of_elems[i]} is greater than {list_of_elems[j]}")
else:
print(f"{list_of_elems[i]} is equal to {list_of_elems[j]}")
输出:
1 is less than 5
1 is less than 2
1 is less than 4
1 is less than 3
5 is greater than 2
5 is less than 4
5 is less than 3
2 is less than 4
2 is less than 3
4 is greater than 3
这个示例代码可以比较列表中所有元素之间的大小关系,并将结果输出到控制台。
下一篇:比较列表中的所有元素。