python - 在 Python 中的列表上循环函数

标签 python list function loops python-3.x

此 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/

相关文章:

Python:列表理解与 lambda

r - 从列表创建和调用线性模型

C函数参数神秘漂移?

Javascript 函数变量

python - 在 scikits learn 中使用 cross_val_score 时保留拟合参数

python - 查找所有出现的正则表达式模式并替换为 eval 输出

python - Flask 上下文处理器在导入的模板中不起作用

java - 由 HashSet 备份的列表

c++ - 如何将类的方法传递给 C++ 中的另一个函数?

python - 无法通过gitpython克隆存储库