我们说我有两个名单:
foo = ['hell', 'good', 'bad']
bar = ['hello', 'goodbye', 'goodness', 'badly', 'baddest']
我想通过foo排序并查看bar中的任何单词是否只匹配但包含foo,以获得类似的内容:
hell = hello
good = goodbye goodness
bad = badly baddest
答案 0 :(得分:4)
one = ['hell','good','bad']
two = ['hello', 'goodbye', 'goodness', 'badly', 'baddest']
for a in one:
print a,'=',
for b in two:
if a in b:
print b,
print
输出:
hell = hello
good = goodbye goodness
bad = badly baddest
答案 1 :(得分:3)
非常简单的问题,有很多方法可以解决它。如果没有匹配项,这里的版本不会打印出“等于”行:
foo = ["hell", "good", "bad", "fail"]
bar = ["hello", "goodbye", "goodness", "badly", "baddest", "nomatch"]
for f in foo:
matches = [b for b in bar if f in b]
if len(matches) > 0:
print(f,"="," ".join(matches))
输出:
hell = hello
good = goodbye goodness
bad = badly baddest
请注意,它不输出'fail'。如果您更愿意打印“失败”一词,请删除if
语句。代码甚至可以减少到一行,虽然我认为这是一个非常难以理解的单行:
[print(f,"="," ".join(b for b in bar if f in b)) for f in foo]