我想通过从每一行中精确选择一个单词来生成句子,并附加这些单词,使得第0行中的单词始终是第一个,第1行中的单词将始终为第二个,依此类推。
E.G。 "这是一只猴子","这里是一只猴子","她是僧侣"
如果有人也能指出相关的通用数学/算法(组合 - 我觉得这是一个组合问题),那将是很棒的。更重要的是,我需要在Python中执行此操作。
sent_matrix = [ ['Here', 'here', 'her', 'ere'],
['is', 'si', 'are', 'was'],
['a', 'the', 'an', 'there'],
['monkey', 'monk-ey', 'mon-key', 'monkee']
]
答案 0 :(得分:2)
您可以使用itertools.product
,如下所示:
import itertools
sent_matrix = [['Here', 'here', 'her', 'ere'],
['is', 'si', 'are', 'was'],
['a', 'the', 'an', 'there'],
['monkey', 'monk-ey', 'mon-key', 'monkee']
]
answer = [' '.join(perm) for perm in itertools.product(*sent_matrix)]
print(answer)
<强>输出强>
['Here is a monkey',
'Here is a monk-ey',
'Here is a mon-key',
'Here is a monkee',
...
'ere was there monkey',
'ere was there monk-ey',
'ere was there mon-key',
'ere was there monkee']
答案 1 :(得分:0)
您可以使用random.choice
尝试:
import random
sent_matrix = [ ['Here', 'here', 'her', 'ere'],
['is', 'si', 'are', 'was'],
['a', 'the', 'an', 'there'],
['monkey', 'monk-ey', 'mon-key', 'monkee']
]
result = ""
for elem in sent_matrix:
result += random.choice(elem) + " "
print result
答案 2 :(得分:0)
如何使用itertools.permutations?
import itertools
n = 4
sent_list = []
for perm in itertools.permutations(range(n)):
random_sent = [sent_matrix[i][j] for (i,j) in enumerate(perm)]
sent_list.append(random_sent)
这对于大n来说可能很慢并且内存昂贵。 如果您只想逐行处理这些随机句子,则应考虑使用yield而不是创建列表。