Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python对两个列表进行可能的对齐_Python_String_List_Alignment - Fatal编程技术网

使用Python对两个列表进行可能的对齐

使用Python对两个列表进行可能的对齐,python,string,list,alignment,Python,String,List,Alignment,我在两个不同的列表中有两个字符串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, hu

我在两个不同的列表中有两个字符串
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 for word Translation

[(i,j) for i in a for j in b]

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

如果你想要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')]
如果需要,您甚至可以获得相关的成对三元组:

>>> 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')]]

这个结果:[(u'hund',u'dog'),(u'hund',u'bit'),(u'hund',u'dog'),(u'bet',u'dog'),(u'bet',u'bit'),(u'bet',u'dog'),(u'hund',u'dog'),(u'hund',u'bit'),(u'hund',u'dog'),(u'hund',u'dog'),(u'hund',u'null')]但是我想为从一个列表到另一个列表的每个可能的对齐设置一个元组。这不是你想要的吗?不,我想在一个元组中设置hung=dog,bet=dog,hung=hund。保留重复项很重要。
>>> 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')]]