以下是一个比较列表的元素和索引的示例代码:
def compare_elements_with_index(lst):
for i in range(len(lst)):
if lst[i] == i:
print(f"元素 {lst[i]} 和索引 {i} 相等")
else:
print(f"元素 {lst[i]} 和索引 {i} 不相等")
# 示例使用
my_list = [0, 1, 2, 3, 4]
compare_elements_with_index(my_list)
输出:
元素 0 和索引 0 相等
元素 1 和索引 1 相等
元素 2 和索引 2 相等
元素 3 和索引 3 相等
元素 4 和索引 4 相等
这个示例中,compare_elements_with_index
函数接受一个列表作为参数。它使用range(len(lst))
迭代列表的索引,并通过比较元素和索引的值,打印出相等或不相等的结果。
上一篇:比较列表的索引并检查条件。