【问题标题】:Looping a function over a list in Python在 Python 中的列表上循环函数
【发布时间】:2015-04-22 00:22:34
【问题描述】:

这个 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。

感谢您的帮助!

【问题讨论】:

  • i &lt; len(a) and len(b) 表示(i &lt; len(a)) and len(b)
  • test-colcol-test 有效配对还是只配对一次?
  • @PadraicCunningham:test-col 和 col-test 都无效。例如,test + col -> tceoslt : 无效 // test + tele -> tteeslte : 无效 // col + test -> ctoelst : 无效 // sho + col -> school : 有效
  • 但它们都出现在列表中?我说的是要传递给联锁的组合
  • 联锁应用于单词的单个字符,而不是单词。感谢您指出这一点!

标签: python list function loops python-3.x


【解决方案1】:

如果您希望列表的所有可能排列都传递给 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)

【讨论】:

    【解决方案2】:

    试试这个。

    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
    

    【讨论】:

    • c = (a[i]+b[i]) IndexError: string index out of range -> 基本上,我的函数只有在所有字符串的字符数相同时才有效
    【解决方案3】:

    您可以使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2013-06-21
      • 2017-01-18
      • 1970-01-01
      • 2021-04-19
      • 2019-04-29
      相关资源
      最近更新 更多