2017-02-09 58 views
-3

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

样品清单:

[<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) 

我怎样才能做到这一点?

+1

'any()'返回一个'bool'。看来你期望它做别的事情? – roganjosh

+0

它需要是“列表”吗?如果你把它当作一个字典,把'state'这个值作为一个关键字,那么这会更方便。 – yedpodtrzitko

+4

'if all(neighbor.state!= s.state for s in stack):' – kindall

回答

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。 (声明:我没有测试这个包。)

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