问题
I have a list of tuples that looks something like this:
my_list = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
I want to get a count of the number combinations regardless of the order. For example, if it were to be simply printed, I'd like the output to be:
1,12 = 3
20,15 = 2
7,8 = 1
Basically, I have a list of connections but the direction doesn't matter, so 1 to 12 is the same as 12 to 1.
I have been working on this for a while and can't come up with a clean solution. Everything I've come up with would have to check for both directions, but the list of tuples is random, so covering every possibility would be ridiculous. I could easily count the unique tuples with set or something, but again, every solution for the "bi-directional" count I've thought about is sloppy.
I feel like this shouldn't be very hard, but I am thoroughly at brain fry from working on this so long. Any help would be greatly appreciated!
回答1:
You can swap all positions by size and then use collections.counter
:
from collections import Counter
l = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
new_l = Counter([[(b, a), (a, b)][a < b] for a, b in l])
for a, b in new_l.items():
print('{},{}:{}'.format(*(list(a)+[b])))
Output:
15,20:2
7,8:1
1,12:3
回答2:
You can use collections.Counter
, normalizing your elements with sorted
first.
from collections import Counter
lst = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
count = Counter(tuple(sorted(t)) for t in lst)
# output: Counter({(1, 12): 3, (15, 20): 2, (7, 8): 1})
You can then print like so.
for value, amount in count.items():
print(value, '=', amount)
# Prints:
# (1, 12) = 3
# (15, 20) = 2
# (7, 8) = 1
回答3:
First you can sort your list
lst2 = [tuple(sorted(i)) for i in lst]
Then you can use set()
to find the unique values in this list and count their occurence.
count = {}
for i in set(lst2):
num = len([1 for j in lst2 if j == i])
count.update({i:num})
print(count)
{(1, 12): 3, (7, 8): 1, (15, 20): 2}
回答4:
You can try simple approach without importing anything like this:
my_list = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
count={}
for i in my_list:
if tuple(sorted(i)) not in count:
count[tuple(sorted(i))]=1
else:
count[tuple(sorted(i))]+=1
print(count)
output:
{(15, 20): 2, (7, 8): 1, (1, 12): 3}
来源:https://stackoverflow.com/questions/49724651/get-count-of-tuples-in-list-regardless-of-elements-orders