0

我在 Python 中设置了一个这样的列表(通过 Ren'Py):

[('nc',nc,'test test test'),('nr',nr,'test test test')]

'nr' 自然是一个字符串,而 nr(不带引号)是一个对象。最后一位是字符串。

现在,我想做的是比较 if 中的整个元组。

像这样的东西:

if (char,charobj,message) not in list:
    #do stuff

这是行不通的——无论如何它仍然可以做事。那么...如何将所有项目与列表中的每个元组进行比较?

4

1 回答 1

0

嗯……

我猜你charobj可能是你自己实现的一个类。为了允许 Python 执行有意义的相等比较而不仅仅是比较,您必须重载默认方法,例如:

  • __eq__(self, other)
  • __gt__(self, other)
  • __lt__(self, other)
  • ...

更多信息:https ://docs.python.org/3/reference/datamodel.html#special-method-names

无论如何,我做了一些测试,它适用于文字和内置类型。我在 Windows 10 (x64) 上使用 Python 2.7。

nr = 4
nc = 2
list = [('nc',nc,'test test test'),('nr',nr,'test test test')]

if ('nc', 2, 'test test test') in list:
    print('OK')
else:
    print('KO')

实际上打印OK

我试过了not in,它打印出来KO

我还尝试用变量替换文字,它似乎也有效。

nr = 4
nc = 2
list = [('nc',nc,'test test test'),('nr',nr,'test test test')]

_nc = 'nc'
_message = 'test test test'
if (_nc, nc, _message) in list:
    print('OK')
else:
    print('KO')

也打印OK

希望有帮助。

于 2018-03-12T17:09:21.307 回答