Python值不在对象列表中

时间:2017-02-09 17:23:13

标签: python python-2.7

我想检查对象列表(堆栈)中是否存在给定值。每个对象都包含我要检查的属性(状态)。

示例清单:

[<state.State instance at 0x02A64580>, <state.State instance at 0x02A646E8>, <state.State instance at 0x02A649B8>]

我尝试过的,似乎并没有这样做:

for neighbor in neighbors:
        if neighbor.state != any(s.state for s in stack):
            stack.append(neighbor)  

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

any()返回bool,如果任何元素为真,则返回true。它基本上是一个链式or。 我想您可能想要的是以下内容:

for neighbor in neighbors:
    present = False
    for s in stack:
        if neighbor.state == s.state:
            present = True
            break
    if not present:
        stack.append(neighbor)

或者,您可能希望使用某种有序集,例如:https://pypi.python.org/pypi/ordered-set。 (免责声明:我没有测试这个包。)

答案 1 :(得分:0)

# setup
class MyObj(object):
    def __init__(self, state):
        self.state = state

states = range(10)
objs = [MyObj(s) for s in states]

neighbor_states = [1,22,5,40,90]
neighbors = [MyObj(s) for s in neighbor_states]

# algorithm
for neighbor in neighbors:
    if neighbor.state not in (o.state for o in objs):
        objs.append(neighbor)

# testing      
for o in objs:
    print o.state