Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of tuples

Tags:

python

tuples

I'm a newbie with python and programming in general and need some help: I have a list that I've created earlier in the program by appending from a loop (i.e. I can't just redefine my list now to solve my problem), of 24 4-tuples:

elementary = [(23, 1, 18, 4), (23, 1, 6, 16), (23, 1, 4, 18), (23, 2, 18, 3), (23, 2, 12, 9), (23, 2, 9, 12), (23, 2, 3, 18), (23, 3, 18, 2), (23, 3, 2, 18), (23, 4, 18, 1), (23, 4, 1, 18), (23, 5, 14, 7), (23, 5, 7, 14), (23, 6, 16, 1), (23, 6, 9, 8), (23, 6, 8, 9), (23, 6, 1, 16), (23, 7, 14, 5), (23, 7, 5, 14), (23, 8, 9, 6), (23, 8, 6, 9), (23, 9, 12, 2), (23, 9, 8, 6), (23, 9, 6, 8), (23, 9, 2, 12), (23, 12, 9, 2), (23, 12, 2, 9), (23, 14, 7, 5), (23, 14, 5, 7), (23, 16, 1, 6), (23, 18, 4, 1), (23, 18, 3, 2), (23, 18, 2, 3), (23, 18, 1, 4)]

but now would like to get rid of the tuples that are just re-arranged... in other words, after the first tuple ((23,1,18,4)) I would let get rid of (23,1,4,18), (23,4,1,18), etc..., and if possible, I'd like to do this throughout the list, so that I only end up with 6 completely distinct 4-tuples. Is there any way to do this without going back and doing something differently earlier in my program? Any help would be greatly appreciated. Thanks!

like image 552
user2006083 Avatar asked Dec 10 '25 20:12

user2006083


2 Answers

How about:

{tuple(sorted(t)): t for t in elementary}.values()
like image 60
wim Avatar answered Dec 12 '25 13:12

wim


As a 1-liner, this sorts each 4-tuple, then creates a set of the result, shich has the effect of removing the duplicates. I'm assuming your 4-tuples are allowed to have the order of elements changed.

set(tuple(sorted(i)) for i in elementary)

>>> set((5, 7, 14, 23), (6, 8, 9, 23), (2, 3, 18, 23), (1, 4, 18, 23), (1, 6, 16, 23), (2, 9, 12, 23))
like image 23
John Lyon Avatar answered Dec 12 '25 11:12

John Lyon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!