简体   繁体   中英

Creating an unique list of tuples of tuples

So I have a list of tuples of tuples that looks like this:

f = [
  ((0, 0), 5, "S"), 
  ((1, 0), 10, "SN"),
  ((0, 0), 8, "SS"),
  ((3, 4), 9, "WN")
...
]

What I want to basically do make a unique list, where the uniqueness of each element of the list depends on the first tuple . For example, from the list above, I need the output to be this:

f = [
  ((0, 0), 5, "S"), 
  ((1, 0), 10, "SN"),
  ((3, 4), 9, "WN")
...
]

Since (0,0) is already there in the list (at index 0), the other (0,0) should not be appended.

Below is the code that I have tried, but it doesn't seem to work:

f = [...]
for i in f:
  if i[0] == (0,0):
    continue
  else:
    f.append(((0,0), val, st))

Can anyone tell me where I'm going wrong or what is the better way of approaching this?

You can use a set() for a fast inclusion check:

seen = set()
new = []

for t in f:
  if t[0] not in seen:
    seen.add(t[0])
    new.append(t)

print(new)

Output:

[((0, 0), 5, 'S'),
 ((1, 0), 10, 'SN'),
 ((3, 4), 9, 'WN')]

Using itertools :

>>> from itertools import groupby
>>> keyfunc = lambda x: x[0]
>>> data = sorted(f, key=keyfunc)
>>> new_f = [ next(v) for _,v in groupby(data, keyfunc)  ]

Results:

>>> new_f
[((0, 0), 5, 'S'), ((1, 0), 10, 'SN'), ((3, 4), 9, 'WN')]

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