【问题标题】:Lists are the same but not considered equal?列表相同但不相等?
【发布时间】:2016-02-21 20:07:44
【问题描述】:

Python 新手遇到相等性测试问题。我有一个列表,states[];每个状态都包含 x,在这种特定情况下 x=3,布尔值。在我的程序中,我生成了一个布尔值列表,其中前三个对应于 state[i]。我遍历测试相等性的状态列表(其中一个肯定是正确的,因为所有可能的布尔排列都在状态中,但从未检测到相等性。不知道为什么,这是我修改的一些代码来测试它:

 temp1 = []
 for boolean in aggregate:
     temp1.append(boolean)
 if len(temp1) == len(propositions):
    break
 print temp1
 print states[0]
 if temp1 == states[0]:
     print 'True'
 else:
     print 'False'

在这种情况下,propisitons 的长度是 3。我从这段代码得到的输出是:

[True, True, True]
(True, True, True)
False

我猜这与括号中的差异有关?与 states[0] 是列表中的列表这一事实有关吗?干杯。

【问题讨论】:

  • states[0] 是一个元组,而不是一个列表。 Brace/parens 风格在 Python 中非常重要。
  • 是的,我现在明白了。我使用了一个内置函数来填充状态,但不知道该函数创建的是元组而不是列表;我什至不知道元组。谢谢,会记住这一点。

标签: python list python-2.7 equality


【解决方案1】:

您正在将 tuple (True, True, True)list [True, True, True]

进行比较

当然它们是不同的。

尝试在旅途中将您的 list 转换为 tuple,以进行比较:

temp1 = []
for boolean in aggregate:
    temp1.append(boolean)
if len(temp1) == len(propositions):
   break
print temp1
print states[0]
if tuple(temp1) == states[0]:
    print 'True'
else:
    print 'False'

或将您的 tuple 投射到 list 进行比较:

temp1 = []
for boolean in aggregate:
    temp1.append(boolean)
if len(temp1) == len(propositions):
   break
print temp1
print states[0]
if temp1 == list(states[0]):
    print 'True'
else:
    print 'False'

输出:

[True, True, True]
(True, True, True)
True

【讨论】:

  • 我使用了一个内置函数来填充状态[],不知道它们被制作成元组;我以前从未使用过元组,必须阅读它们,非常感谢。
  • @Bergy24 很高兴我的回答有所帮助。如果它帮助您解决问题,请不要忘记接受我的回答:)
猜你喜欢
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 2017-12-06
相关资源
最近更新 更多