【问题标题】:Possible alignments of two lists using Python使用 Python 可能对齐两个列表
【发布时间】:2013-01-25 07:03:16
【问题描述】:

我在两个不同的列表A = [dog bit dog null]B = [hund bet hund] 中有两个字符串。 我想从列表 B 到列表 A 中找到所有可能的对齐方式,例如:

  C =  [(hund = dog, bet = bit, hund = dog),
        (hund = dog, bet = bit, hund = bit),
        (hund = dog, bet = bit, hund = null),
        (hund = dog, bet = dog, hund = dog),
        (hund = dog, bet = dog, hund = bit),
        etc.. ]

我认为这两个字符串之间有 64 种不同的对齐方式。 我正在研究用于单词翻译的 IBM model1。

【问题讨论】:

    标签: python string list alignment


    【解决方案1】:
    [(i,j) for i in a for j in b]
    

    你不能在列表中拥有这种结构,你需要一个字典,我在这里使用一个元组来关联值。

    【讨论】:

    • 这个结果:[(u'hund', u'dog'), (u'hund', u'bit'), (u'hund', u'dog'), (u 'hund', u'null'), (u'bet', u'dog'), (u'bet', u'bit'), (u'bet', u'dog'), (u'bet ', u'null'), (u'hund', u'dog'), (u'hund', u'bit'), (u'hund', u'dog'), (u'hund', u'null')] 但我想为从一个列表到另一个列表的每个可能对齐有一个元组。
    • 这不是你想要的吗?
    • 不,我想在一个元组中挂起 = 狗,赌注 = 狗,挂起 = hund
    【解决方案2】:

    如果你想要这 64 种可能性,你可以使用itertools.product:

    >>> from itertools import product
    >>> A = "dog bit dog null".split()
    >>> B = "hund bet hund".split()
    >>> product(A, repeat=3)
    <itertools.product object at 0x1148fd500>
    >>> len(list(product(A, repeat=3)))
    64
    >>> list(product(A, repeat=3))[:5]
    [('dog', 'dog', 'dog'), ('dog', 'dog', 'bit'), ('dog', 'dog', 'dog'), ('dog', 'dog', 'null'), ('dog', 'bit', 'dog')]
    

    但请注意,鉴于您在 A 中有两次 dog

    >>> len(set(product(A, repeat=3)))
    27
    

    如果你愿意,你甚至可以得到相关的三元组:

    >>> trips = [zip(B, p) for p in product(A, repeat=len(B))]
    >>> trips[:5]
    [[('hund', 'dog'), ('bet', 'dog'), ('hund', 'dog')], [('hund', 'dog'), ('bet', 'dog'), ('hund', 'bit')], [('hund', 'dog'), ('bet', 'dog'), ('hund', 'dog')], [('hund', 'dog'), ('bet', 'dog'), ('hund', 'null')], [('hund', 'dog'), ('bet', 'bit'), ('hund', 'dog')]]
    

    【讨论】:

    • 保留副本很重要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    相关资源
    最近更新 更多