【问题标题】:How to Check if elements of two lists are equal or not using IF statement in python?python - 如何在python中使用IF语句检查两个列表的元素是否相等?
【发布时间】:2022-01-10 14:35:51
【问题描述】:

我有一个多维列表。我想检查不同列表的元素是否相等或仅使用 if 语句。 我使用 for 循环和 while 循环编写了不同的版本。我不知道如何仅使用 if 语句来做同样的事情。

以下是我的代码。

A =      [[[1], [2]],
          [[3], [4]],
          [[5], [6]],
          [[7], [8]],
          [[7], [8]]]  

# Checking if two lists are equal or not using for loop
for i in range(len(A)-1):
    if A[i] == A[i+1]:
        print('iteration',[i],'=',A[i],'and','iteration',[i+1],'=',A[i+1],'are equal')

输出

iteration [3] = [[7], [8]] and iteration [4] = [[7], [8]] are equal

使用while循环

# # Checking if two lists are equal or not using while loop
i = 1
while i in range(0, len(A)-1):
    if A[i] == A[i+1]:
        print('iteration',[i],'=',A[i],'and','iteration',[i+1],'=',A[i+1],'are equal')
    
    i = i+1

输出

iteration [3] = [[7], [8]] and iteration [4] = [[7], [8]] are equal

如何仅使用 if 语句达到相同的结果?

【问题讨论】:

  • 所以你想在外部列表中找到连续的重复项?
  • 是的,你可以这么说。

标签: python-3.x for-loop if-statement while-loop


【解决方案1】:

您不能只使用 if 语句来编写代码。当您不知道列表有多长时,如果语句无法遍历列表的长度。您需要查看每个索引以确定它是否等于第二个列表中的索引。如果您确实知道列表有多长,那么您必须为列表中的每个索引写出不同的条件。最有效的编码方式就是你的方式 做到了(使用 for 循环或 while 循环)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 2013-03-21
    • 1970-01-01
    • 2020-06-13
    • 2021-03-30
    • 2012-04-03
    • 1970-01-01
    • 2013-12-02
    相关资源
    最近更新 更多