0

我在两个不同的列表中有两个字符串,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 的单词翻译。

4

2 回答 2

1

如果你想要 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')]

但请注意,这将产生相当数量的重复,因为您有dog两次A

>>> 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')]]
于 2013-02-09T20:13:08.583 回答
0
[(i,j) for i in a for j in b]

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

于 2013-02-09T20:09:10.757 回答