Python:替换列表项并生成所有可能的排列

时间:2017-11-22 15:43:31

标签: python-3.x python-2.7 list

我正在尝试为部分莫尔斯码实现莫尔斯解码。例如,莫尔斯电码中的单词TEST的表示是[' - ','。',&# 39; ...',' - ']但是,如果每个莫尔斯代码字符串的第一个字符缺失并由x表示,则TEST的部分莫尔斯代码将变为[' x& #39;,' x',' x ..',' x']。因此,为了解码此部分消息,我们将不得不替换x与任何一个。或 - 对于上述部分莫尔斯码中x的每次出现。使用' x'未知解码时TEST字的排列将是ETST,EEDT,ETSE等。我已经实现了莫尔斯部分解码功能如下:

def morsePartialDecode(inputStringList):
    with open('words.txt','a') as wordfile:
        dictionaryFileLoc = './dictionary.txt'
        message_received = inputStringList
        message_received = ' '.join(inputStringList)
        for i in range(len(message_received)):
            x = 'x'
            y = '.'
        message = message_received.replace(x, y)
        message1 = message.split(",")
        message_converted = morseDecode(message1)
        print message_converted
        print >> wordfile, (message_converted)
        for i in range(len(message_received)):
            x = 'x'
            y = '-'
        message = message_received.replace(x, y)
        message2 = message.split(",")
        message_converted = morseDecode(message2)
        print >> wordfile, (message_converted)
        elements = []
    wordfile.closed
    return message_converted

def partialMorseCodeTest():
    test = ['x', 'x', 'x..', 'x']
    print morsePartialDecode(test)  

partialMorseCodeTest()

Output:
EESE
TTDT

我需要[' x',' x',' x ..',' x']的所有组合x替换为。或者 - 我的morseDecode()会将每个组合转换为相应的单词,如EESE,TTDT等morsedecode)怎么做。谢谢!

1 个答案:

答案 0 :(得分:1)

itertools的好例子

使用itertools.product的示例:

from itertools import product

def replace_x_with_all_combinations(morse):
    # only works with 1 and 1 only 'x' in each element
    all_perm = list()
    for v in morse:
        if 'x' in v:
            # create a list of permutations per element of the morse list
            # and append them to the all_perm list
            all_perm.append([v.replace('x','.'), v.replace('x','-')])
        else:
            # if no x found, then append the original element
            all_perm.append([v])
    # all_perm = [['.', '-'], ['.', '-'], ['...', '-..'], ['.', '-']]
    # the list all_perm needs to be unpacked before passing
    # to the product() generator, hence the *
    return list(product(*all_perm))

partial = ['x','x','x..','x']
result = replace_x_with_all_combinations(partial)
for e in result:
    print(e)

输出:

('.', '.', '...', '.')
('.', '.', '...', '-')
('.', '.', '-..', '.')
('.', '.', '-..', '-')
('.', '-', '...', '.')
('.', '-', '...', '-')
('.', '-', '-..', '.')
('.', '-', '-..', '-')
('-', '.', '...', '.')
('-', '.', '...', '-')
('-', '.', '-..', '.')
('-', '.', '-..', '-')
('-', '-', '...', '.')
('-', '-', '...', '-')
('-', '-', '-..', '.')
('-', '-', '-..', '-')

[编辑] 虽然我自己将限制放在上面的代码中,但“莫尔斯字符中只有1 x的作品”让我感到烦恼,所以下面的例子将从莫尔斯字符中删除多个数字,超过一个'x'

from itertools import product


def replace_x_in_morse_charcter(morse_character):
    all_perm = [['.','-'] if c == 'x' else [c] for c in morse_character]
    p = list(product(*all_perm))
    return [''.join([v for v in e]) for e in p]


def replace_x_in_morse_word(morse):
    all_perm = [replace_x_in_morse_charcter(c) for c in morse]
    return list(product(*all_perm))


partial = ['x','x','x..','xx']
result = replace_x_in_morse_word(partial)
for e in result:
    print(e)

[编辑]为了一个单一的乐趣:

morse_word = ['x','x','x..','xx']
result = list(product(*[[''.join([v for v in e]) for e in list(product(*[['.','-'] if c == 'x' else [c] for c in cm]))] for cm in morse_word]))