在Python中循环使用列表中的函数

时间:2015-02-20 10:42:18

标签: 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。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

您可以使用itertools模块中的产品功能来执行此操作:

from itertools import product

for a, b in product(word_list, word_list):
    interlock(a, b)

https://docs.python.org/2/library/itertools.html#itertools.product

答案 1 :(得分:1)

如果您希望列表的所有可能排列都传递到互锁而不将单词与自身配对,即我们不会得到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

您还可以使用""使用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) 的填充值来捕获较长单词的结尾,从而获得相同的结果:

{{1}}

答案 2 :(得分:0)

试试这个。

def interlockList(A):
    while Len(A) > 2:
      B = interlock(A[0],A[1])
      A.remove(A[0])
      A.remove(A[1])
      A.insert(0, B)
    return B