如何将像矢量这样的单词列表相乘? [英] How to multiply lists of words like vectors?

查看:66
本文介绍了如何将像矢量这样的单词列表相乘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的单词列表(这里只列出了2个):

I have lists of words like this (only 2 listed here):

list_1 = ['average', 'reasonable'] 
list_2 = ['fiddle', 'frolic']
list_n = ['etc', 'etc']

我希望将这两个列表相乘以获得答案:

I wish to multiply these two lists together to obtain this answer:

obj[l1] * obj[l2] = ['average fiddle', 'average frolic', 'reasonable fiddle', 'reasnable frolic']
obj[l1] * obj[l2] *...* obj[n]

我写了这段代码:

import numpy as np
obj = {}
obj['l1'] = np.array(list_1)
obj['l2'] = np.array(list_2)
print(obj['l1']*obj['l2'])

但这只会给我一个错误:

But that only gives me an error:

TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('<U10') dtype('<U10') dtype('<U10')

我该怎么办?

尝试使用itertools,如下所示:

Tried using itertools like the user below suggested:

word_list = ['fair play']
output = {'fair': ['average', 'reasonable'], 'play': ['fiddle', 'frolic']}
result = []
for words in word_list: 
    for word in word_tokenize(words): 
        list_1 = output_set[word]
        result = [(x, y) for x, y in product(list_1, result)]
        result = list(map(' '.join, result))
print(result)

但这只会返回一个空集.有没有办法遍历无限"列表?

But this only returns an empty set. Is there a way to iterate through 'infinite' lists?

推荐答案

使用 itertools.product ,我们可以将它们获取为tuples,然后使用' '.join创建str

Using itertools.product we could obtain these as tuples and then use ' '.join to create str's

from itertools import product

list_1 = ['average', 'reasonable'] 
list_2 = ['fiddle', 'frolic']
list_n = ['etc', 'vash']

a = [(x, y, z) for x, y, z in product(list_1, list_2, list_n)]
a = list(map(' '.join, a))
# ['average fiddle etc', 'average fiddle vash', 'average frolic etc', 'average frolic vash', 'reasonable fiddle etc', 'reasonable fiddle vash', 'reasonable frolic etc', 'reasonable frolic vash']

这篇关于如何将像矢量这样的单词列表相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆