你需要每一個項目列表與列表中的每個其他項目相比,除了本身(因爲這會產生假陽性 - 這將永遠是正確的,因爲任何字符串在技術上是自己的後綴)。
所以,考慮到這一點,類似下面的東西應該工作。我測試了針對三種不同的輸入列表,其中包括一個不應該在所有的匹配(並且不):
#!/usr/bin/env python
words_list = ['hello', 'lo', 'he']
words_list2 = ['narf', 'poit', 'troz']
words_list3 = ['narf', 'narfpoit', 'troznarf', 'zort']
def check_words(words_list):
print "#####"
for outer_num, outer_word in enumerate(words_list):
print "Outer word #{0}: {1}".format(outer_num, outer_word)
for inner_num, inner_word in enumerate(words_list):
print "Inner word #{0}: {1}".format(inner_num, inner_word)
if outer_num != inner_num:
if outer_word.endswith(inner_word):
print "True"
return True
else:
print "False"
return False
result = check_words(words_list)
print "result: {0}".format(result)
result = check_words(words_list2)
print "result: {0}".format(result)
result = check_words(words_list3)
print "result: {0}".format(result)
這將產生以下的輸出:
#####
Outer word #0: hello
Inner word #0: hello
Inner word #1: lo
True
result: True
#####
Outer word #0: narf
Inner word #0: narf
Inner word #1: poit
False
Inner word #2: troz
False
Outer word #1: poit
Inner word #0: narf
False
Inner word #1: poit
Inner word #2: troz
False
Outer word #2: troz
Inner word #0: narf
False
Inner word #1: poit
False
Inner word #2: troz
result: False
#####
Outer word #0: narf
Inner word #0: narf
Inner word #1: narfpoit
False
Inner word #2: troznarf
False
Inner word #3: zort
False
Outer word #1: narfpoit
Inner word #0: narf
False
Inner word #1: narfpoit
Inner word #2: troznarf
False
Inner word #3: zort
False
Outer word #2: troznarf
Inner word #0: narf
True
result: True
注:額外打印語句僅用於說明目的 - 這些可以被註釋掉。
是否有原因返回True,但打印False? – SethMMorton 2014-09-01 00:04:27