简体   繁体   中英

Looping a function over a list in Python

This Python function interlocks the characters of two words (eg, "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")

Now, I would like to apply this function to a list of words. The goal is to find out any interlock corresponds to an item of a list.

word_list = ["test", "col", "tele", "school", "tel", "sho", "aye"]

To do that, I would first have to create a new list that has all the interlocks in it. This is exactly where I am stuck - I don't know how to iterate over word_list using interlock.

Thanks for your help!

You can do it using product function from itertools module:

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

If you want all possible permutations of the list to pass to interlock without pairing a word with itself ie we won't get 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

You can also achieve the same result using itertools.zip_longest using a fillvalue of "" to catch the end of the longer words:

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)

Try this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM