Home > Net >  Generate pairs of users from list
Generate pairs of users from list

Time:11-29

trying to create a function which generates pairs of users from list. Everyone have to get a pair. Example list of user IDs:

list = [123, 456, 789]
...smth...
result =  {123:456, 456:789, 789:123} — OK
list = [123, 456, 789]
...smth...
result =  {123:456, 456:123, 789:789} — BAD
list = [123, 456, 789, 234, 678]
...smth...
result = {123:456, 456:123, xxxxx} - BAD

Trying to do this in python but cant find a solution

Tried lists, sets, dicts, but cant find an alghoritm

CodePudding user response:

Assuming the pairs to be tuples, you can use itertools.combinations.

From the docs (table on top of the page):

r-length tuples, in sorted order, no repeated elements

And:

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeated values in each combination.

This means that if you have a tuple with equal values, like (123, 123) , then you will get both (123, x) and (x, 123).

from itertools import combinations

data = [123, 456, 789]

result = list(combinations(data, 2)) # [(123, 456), (123, 789), (456, 789)]

Also, avoid using the "list" word for naming, as list is a Python container.

CodePudding user response:

Your question is definitely not clear and you should read a bit more about how to ask questions and show what code you have tried and failed. But if I understand correctly, the pairs will be consecutive. I.e. first item with the second, second with the third, and so on, until the last item pairs with the first, and you're showing in your example a dictionary structure, so maybe you can use a function like this.

def make_pairs(input_list):
    out_dict = dict()  # output dictionary
    for i in range(len(input_list)):  # i is from 0 to len(list) - 1
        # if i is not pointing to the last item
        if not i == len(input_list) - 1:
            # make pair from the i-th item and the (i 1) item
            out_dict[input_list[i]] = input_list[i 1]
        # i points to the last item
        else:
            # make pair from the last item and the first item
            out_dict[input_list[i]] = input_list[0]
    return out_dict

input_list = [123, 456, 789]
out_dict = make_pairs(input_list)
print(out_dict)

Of course, this is somewhat of a bad solution, but you did not give enough information, for example, if the list has repeating items, then keys will overwrite each other.

As mentioned above, avoid using list as a variable name, it's a reserved Python keyword.

  • Related