2017-02-09 2 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

'list'가 필요합니까? 'state' 값을 키로 사용할 수있는 딕트 (dict)가 있다면 훨씬 편리 할 것입니다. – yedpodtrzitko

+4

'모든 것 (스택에있는 s에 대한 neighbor.state! = s.state) :' – kindall

답변

0

any()은 요소 중 하나라도 true이면 bool을 반환합니다. 기본적으로 연결된 체인 or입니다. https://pypi.python.org/pypi/ordered-set :

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

또한,이처럼 명령 세트의 어떤 종류를 사용 할 수 있습니다 : 나는 당신이 할 수 있습니다하면 다음과 같이 생각합니다. (부인 :이 패키지를 테스트하지 않았다.)

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 
관련 문제