此 Python 函数将两个单词的字符互锁(例如,“sho”+“col”->“school”)。 word1-char1 + word2-char1 + word1-char2 + ...
def interlock(a,b):
i = 0
c = ""
d = ""
while (i < len(a) and len(b)):
c = (a[i]+b[i])
d = d + c
i+=1
return(d)
interlock("sho", "col")
现在,我想将此函数应用于单词列表。目标是找出与列表项对应的任何互锁。
word_list = ["test", "col", "tele", "school", "tel", "sho", "aye"]
为此,我首先必须创建一个包含所有互锁的新列表。这正是我卡住的地方——我不知道如何使用互锁迭代 word_list。
感谢您的帮助!
最佳答案
如果您希望列表的所有可能排列传递给 interlock 而无需将单词与自身配对,即我们不会得到 interlock("col", "col")
:
def interlock(s1,s2):
out = ""
while s1 and s2: # keep looping until any string is empty
out += s1[0] + s2[0]
s1, s2 = s1[1:], s2[1:]
return out + s1 + s2 # add the remainder of any longer string
word_list = ["test", "col", "tele", "school", "tel", "sho","col" "aye"]
from itertools import permutations
# get all permutations of len 2 from our word list
perms = permutations(word_list,2)
st = set(word_list)
for a, b in perms:
res = interlock(a,b)
if res in st:
print(res)
school
您也可以使用 itertools.zip_longest 获得相同的结果使用 ""
的填充值来捕捉较长单词的结尾:
from itertools import permutations, zip_longest
perms = permutations(word_list, 2)
st = set(word_list)
for a, b in perms:
res = "".join("".join(tup) for tup in zip_longest(a,b,fillvalue=""))
if res in st:
print(res)
关于python - 在 Python 中的列表上循环函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28627009/