2014-01-21 3 views
0

안녕하세요.이 코드는 파이썬 목록에서 항목을 선택하는 데 사용됩니다.While 루프가 잘 작동하지 않습니다.

import re 
name = input 
while True: 
    name = input("Please enter your search term here:").lower() 
    def FindName(name,list1): 
     """ searches for a pattern in the list, returns the complete list entry. Is case  sensitive. 
May return incomplete value if ' is in the list value (ie confucius's)""" 
    if name in list1: 
     return name 
    else: 
     string1 = str(list1).replace('"',"'") 
     pattern = re.compile("[']"+name+"[^']*") 
     match = re.search(pattern,string1) 
     if match: 
      if match.group().lstrip("'") in list1: 
       return match.group().lstrip("'") 
      else: 
       print 'Fail %s' %match.group().lstrip("'") 
       return None 
     else: 
      return ' '.join(name2) 
    china=['In', 'China', 'people', 'teach',"Confusius's", 
    'teachings','dilligently.','Those',"Confusius''s", 
    'teachings','are','called','Taoism.'] 
    india=['India', 'bopal', 'mahindra', 'gujarat',"gandhi's", 
    'bombay',"Gandhi",]  ] 

    name2 = name[:] 
    this= ' '.join(name2) 
    print FindName(this,china) 
    for item in china:    
     print [(i,x) for (i,x) in enumerate(china) if x.startswith(this)] 
    this = ' '.join(name2) 
    for item in india: 
     print [(i,x) for (i,x) in enumerate(india) if x.startswith(this)] 
    this = ' '.join(name2) 
    for item in india: 
     print [(i,x) for (i,x) in enumerate(india) if x.endswith(this)] 
    this = ' '.join(name2) 
    for item in india: 
     print [(i,x) for (i,x) in enumerate(china) if x.startswith(this)] 
    loop continues...... 

문제는 내가 루프에 휴식을 넣어 시도한다는 것입니다하지만 여전히 인쇄 : 문제는

이상 코드를 루프 번이다 모든 루프에 print [(i,x) for (i,x) in enumerate...는 루프 아래로갑니다. 어떻게 문을 반복 할 수 있지만 루핑 및 인쇄없이 원하는 항목 만 인쇄합니다 print [(i,x) for (i,x) in enumerate(china) if x.startswith(this)] 등?

답변

0

각 결과에 대해 인쇄물을 두 배로 늘린 것 같습니다. 이 대신 :

for item in china:    
    print [(i,x) for (i,x) in enumerate(china) if x.startswith(this)] # will print relevant index and item of china once for every item in china 

이 시도 :

for index, item in enumerate(china): 
    if item.startswith(this): 
     print (index, item) # will print each relevant index and item in china only once 

나이 :

print [(i,x) for (i,x) in enumerate(china) if x.startswith(this)] # no for-loop 

을 각 루프에 대해. 당신이 더 큰 반면 루프의 탈옥하려는 경우, 당신은을 위해 - 루프의 break외부를 삽입해야합니다 : 입력에 대한

while True: 
    ... 
    if <something>: 
     break 
    for ... 
+0

HEY 모두 감사합니다. 그것은 가치! – wakamdr

관련 문제