简体   繁体   中英

Python fastest method to group pairs from a list of items

As a part of my project, I need to group characters as pairs (unique). I have more than 1000 of these characters in a list. What would be the fastest and optimized method to create unique pairs out of these list of characters. I am using itertools currently and my code seems to perform pretty badly.

My Code using itertools:

import itertools

characters = ['A', 'B', 'C', 'D', 'E']
relations = []
for character in range(len(characters) + 1):
    for combination in itertools.combinations(characters, character):
        if len(combination) == 2:
            relations.append(combination)
print relations

Expected Output:

[('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'C'),   
('B', 'D'), ('B', 'E'), ('C', 'D'), ('C', 'E'), ('D', 'E')]

All you need are combinations of length 2?

In [48]: characters = ['A', 'B', 'C', 'D', 'E']

In [50]: list(itertools.combinations(characters, 2))
Out[50]:
[('A', 'B'),
 ('A', 'C'),
 ('A', 'D'),
 ('A', 'E'),
 ('B', 'C'),
 ('B', 'D'),
 ('B', 'E'),
 ('C', 'D'),
 ('C', 'E'),
 ('D', 'E')]

You are also generating combinations of length 3 to len(characters) and throwing them all away.

characters = ['A', 'B', 'C', 'D', 'E']
relations = list(itertools.combinations(characters, 2))

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