这个问题的灵感来自:Generating a list of repetitions regardless of the order及其接受的答案:https://stackoverflow.com/a/20336020/1463143
在这里,“alphabet”是任意一组字母,例如'012' 或 'EDCRFV'
“单词”是通过对字母表进行笛卡尔积得到的。我们应该能够指定 n
来获取 n 个字母的单词。示例:
from itertools import product
alphabet = '012'
wordLen = 3
wordList = [''.join(letter) for letter in product(alphabet,repeat=wordLen)]
print wordList
给出:
['000', '001', '002', '010', '011', '012', '020', '021', '022', '100', '101', '102', '110', '111', '112', '120', '121', '122', '200', '201', '202', '210', '211', '212', '220', '221', '222']
“同义词”是通过……呃……要是我能说清楚就好了……
这些列表包含 wordList
中所有可能的“同义词”:
['000',
'111',
'222']
['001',
'002',
'110',
'112',
'220',
'221']
['010',
'020',
'101',
'121',
'202',
'212']
['011',
'022',
'100',
'122',
'200',
'211']
['012',
'021',
'102',
'120',
'201',
'210']
遗憾的是,我无法清楚地说明我是如何获得上述“同义词”列表的。我想对形成 n 个字母的单词的任意字母表执行上述操作。
最佳答案
看起来很简单:
syns = collections.defaultdict(list)
for w in wordList:
hash = tuple(w.index(c) for c in w)
syns[hash].append(w)
print syns.values()
关于python - 概念:从 "synonyms"列表中收集 "words",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20351205/