您好我有这个代码从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 :(得分: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循环,则需要在for循环之外插入break
:
while True:
...
if <something>:
break
for ...