简体   繁体   中英

Tuple of Pairs from List of Integers

I am trying to create a list of tuple pairs from a list of integers. The list of tuple pairs will contain pairs of numbers found in the list. Example below:

listofint = [4, 3, 1, 2, 3, 1, 1, 3, 5, 1, 2, 2]
listoftuplepairs = [(3,3),(1,1),(2,2),(1,1)]

I am confused how I can implement this using a list comprehension. I have tried this below but it only returned an empty string.

listoftuplepairs = [(i,listofint.remove(i)) for i in listofint if listofint.remove(i) == i]

I understand using remove() on a list does not return anything. I have experimented with pop() but I can only pass to it a list index as the argument, instead of the actual value I want to pop() and store in my list of tuples.

Is there any other way to do this via list comprehension?

You can try this using Counter

Counter is used to count the number of occurrences of hashable objects.

from collections import Counter
l=[4, 3, 1, 2, 3, 1, 1, 3, 5, 1, 2, 2]
c=Counter(l)
# Counter({4: 1, 3: 3, 1: 4, 2: 3, 5: 1})

[(k,k) for k,v in c.items() for _ in range(v//2)]
# [(3, 3), (1, 1), (1, 1), (2, 2)]

So, here key k would be the number and value v would be the number of times it occurred in the list. Since you wanted pairs to get the number of pairs I did v//2 . The above approach in one-line list comprehension would be

[(k,k) for k,v in Counter(l).items() for _ in range(v//2)]

Using dict.fromkeys . Just mimicking what Counter does here.

c=dict.fromkeys(l,0)
for k in l:
    c[k]+=1

[(k,k) for k,v in c.items() for _ in range(v//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