简体   繁体   中英

How to create a list of word pairs

I want to create a list of word pairs, separated by tabs, from a word list. I think one option could be to create a matrix with "range" because i want to have all words combined with each other. I need the list of word pairs to make further analyses.

From a word list:

mama
papa
sister
brother

should be the output

mama papa
sister brother
mama sister
papa sister
brother mama

and so on....

Someone who knows what would be the best way to do this?

words = ["mama", "papa", "sister", "brother"]
pairs = list(itertools.product(words, repeat=2))
print pairs

prints

[('mama', 'mama'),
 ('mama', 'papa'),
 ('mama', 'sister'),
 ('mama', 'brother'),
 ('papa', 'mama'),
 ('papa', 'papa'),
 ('papa', 'sister'),
 ('papa', 'brother'),
 ('sister', 'mama'),
 ('sister', 'papa'),
 ('sister', 'sister'),
 ('sister', 'brother'),
 ('brother', 'mama'),
 ('brother', 'papa'),
 ('brother', 'sister'),
 ('brother', 'brother')]
words = ["mama", "papa", "sister", "brother"]
pairs = list(itertools.permutations(words, 2))
print pairs

Note the use of permutations which I think is what you may be asking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM