【问题标题】:I need to find out if two lists are equal in terms of reference, equal in terms of value or not equal我需要找出两个列表在参考方面是否相等,在价值方面是否相等或不相等
【发布时间】:2017-01-11 06:27:57
【问题描述】:
def type_of_equality(list1, list2):
    new_string = ""
    if list1 == list2:
        new_string += "value"
        return new_string
    elif list1 != list2:
        new_string += "not equal"
        return new_string
    elif list1 is list2:
        new_string += "reference"
        return new_string

当我尝试这个时

x = [1,2,3]
y = x
print(type_of_equality(x, y))

输出应该是参考,但输出是相等的。我该如何解决这个问题。

【问题讨论】:

  • x == yx is y 也是,但从来没有出现过。
  • 那是您比参考值更早地检查值!
  • 哦,我明白了。我的错。
  • 只返回字符串,不需要 +=

标签: python python-3.x equality


【解决方案1】:

您应该在检查是否相等之前检查list1 is list2

当 x 为 y 时,x 始终等于 y。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多