简体   繁体   中英

Creating unique pairs from a list of particles

I already have code where I make unique pairs of proton and neutrons which are stored in the lists self.p and self.n respectively. I would also like to get unique pairs of protons and unique pairs of neutrons from these two lists.

Code to make proton-neuteron pairs:

 for proton in self.p:
            for neutron in self.n:
                self.pn_combinations.append([proton, neutron])

I cannot simply iterate twice over self.p to create unique pairs of protons, as list will contain duplicates and same set pairs just in reversed order. So I am not sure how to proceed.

Eg self.p can contain 3 particles of:

self.p =  [[1,2,3,4], [5,6,7,8], [9, 10, 11, 12]]

And would like to output:

Pairs = [[[1,2,3,4], [5,6,7,8]],[[1, 2, 3, 4],[9,10,11,12]], [[5,6,7,8], [9,10,11,12]]] 

where each item in pairs is a unique combination of protons in self.p

You may just treat each particles as an element and use itertools.combinations()

from itertools import combinations
p =  [[1,2,3,4], [5,6,7,8], [9, 10, 11, 12]]
pairs = [list(combination) for combination in combinations(p, 2)]
print(pairs)

output: [[[1, 2, 3, 4], [5, 6, 7, 8]], [[1, 2, 3, 4], [9, 10, 11, 12]], [[5, 6, 7, 8], [9, 10, 11, 12]]]

You can use the second loop from one index up then the outer loop is in:

p =  [[1,2,3,4], [5,6,7,8], [9, 10, 11, 12]]

particels = []
for i, part in enumerate(p):
    for part2 in p[i+1:]:
        particels.append( (part ,part2) )

print(particels)

Output:

[([1, 2, 3, 4], [5, 6, 7, 8]), 
 ([1, 2, 3, 4], [9, 10, 11, 12]), 
 ([5, 6, 7, 8], [9, 10, 11, 12])]

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