Python 获取矩阵中所有可能的行组合
我正在用python设置一个简单的句子生成器,创建尽可能多的单词组合来描述一组涉及机器人的通用图像。(说来话长:D) 它输出如下内容:“电子人概念可下载插图” 令人惊讶的是,我写的随机生成只增加到255个独特的组合。以下是脚本:Python 获取矩阵中所有可能的行组合,python,numpy,matrix,Python,Numpy,Matrix,我正在用python设置一个简单的句子生成器,创建尽可能多的单词组合来描述一组涉及机器人的通用图像。(说来话长:D) 它输出如下内容:“电子人概念可下载插图” 令人惊讶的是,我写的随机生成只增加到255个独特的组合。以下是脚本: import numpy from numpy import matrix from numpy import linalg import itertools from pprint import pprint import random m = matrix(
import numpy
from numpy import matrix
from numpy import linalg
import itertools
from pprint import pprint
import random
m = matrix( [
['Robot','Cyborg','Andoid', 'Bot', 'Droid'],
['Character','Concept','Mechanical Person', 'Artificial Intelligence', 'Mascot'],
['Downloadable','Stock','3d', 'Digital', 'Robotics'],
['Clipart','Illustration','Render', 'Image', 'Graphic'],
])
used = []
i = 0
def make_sentence(m, used):
sentence = []
i = 0
while i <= 3:
word = m[i,random.randrange(0,4)]
sentence.append(word)
i = i+1
return ' '.join(sentence)
def is_used(sentence, used):
if sentence not in used:
return False
else:
return True
sentences = []
i = 0
while i <= 1000:
sentence = make_sentence(m, used)
if(is_used(sentence, used)):
continue
else:
sentences.append(sentence)
print str(i) + ' ' +sentence
used.append(sentence)
i = i+1
导入numpy
从numpy导入矩阵
来自numpy import linalg
进口itertools
从pprint导入pprint
随机输入
m=矩阵([
[“机器人”、“电子人”、“机器人”、“机器人”、“机器人”],
[‘性格’、‘概念’、‘机械人’、‘人工智能’、‘吉祥物’],
[“可下载”、“库存”、“3d”、“数字”、“机器人技术”],
[‘剪贴画’、‘插图’、‘渲染’、‘图像’、‘图形’],
])
已用=[]
i=0
def make_语句(m,已使用):
句子=[]
i=0
而i则可以使用itertools获得矩阵的所有可能组合。我举了一个例子来说明itertools是如何工作的
import itertools
mx = [
['Robot','Cyborg','Andoid', 'Bot', 'Droid'],
['Character','Concept','Mechanical Person', 'Artificial Intelligence', 'Mascot'],
['Downloadable','Stock','3d', 'Digital', 'Robotics'],
['Clipart','Illustration','Render', 'Image', 'Graphic'],
]
for combination in itertools.product(*mx):
print combination
您的代码可以使用递归。如果没有itertools,这里有一个策略:
def make_sentences(m, choices = []):
output = []
if len(choices) == 4:
sentence = ""
i = 0
#Go through the four rows of the matrix
#and choose words for the sentence
for j in choices:
sentence += " " + m[i][j]
i += 1
return [sentence] #must be returned as a list
for i in range(0,4):
output += make_sentences(m, choices+[i])
return output #this could be changed to a yield statement
这与您原来的函数大不相同
选项列表跟踪m中已选择的每一行的列索引。当递归方法发现选择了四行时,它输出一个只有一句话的列表
当该方法发现选项列表没有四个元素时,它会递归地调用自己四个新的选项列表。这些递归调用的结果将添加到输出列表中 ??