2014-01-21 217 views
0

嗨我有這個代碼從python列表中選擇項目。問題是,一旦它遍歷雖然循環工作不正常

CODE:

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 

每個for循環。如果你想打出來的大while循環,你將需要插入break外面的for循環:

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

嘿所有,感謝您的輸入。這很值得! – wakamdr