Sort the tuple list

I have a list of tuples of the form (a, b, c, d), and I want to copy only those tuples with unique 'a' values ​​to the new list. I am very new to python.

Current idea that doesn't work:

for (x) in list:
   a,b,c,d=(x)
   if list.count(a)==1:
      newlist.append(x)
+1
source share
4 answers

If you do not want to add any tuples that have duplicate values a(as opposed to adding the first occurrence of a given a, but not one of the last):

seen = {}
for x in your_list:
    a,b,c,d = x
    seen.setdefault(a, []).append(x)

newlist = []
for a,x_vals in seen.iteritems():
    if len(x_vals) == 1:
        newlist.append(x_vals[0])
+3
source
values = {}

for t in tups:
  a,b,c,d = t
  if a not in values:
    values[a] = (1, t)
  else:
    count, tup = values[a]
    values[a] = (count+1, t)

unique_tups = map(lambda v: v[1],
                  filter(lambda k: k[0] == 1, values.values()))

a , a. (count, tuple), count - , a.

values a , count 1, .. . , , count 1.

unique_tups a.

, !

+2

:

seen_a = set()
for x in list:
    a, b, c, d = x
    if a not in seen_a:
        newlist.append(x)
        seen_a.add(x)
+2

you can really sort the list and then iterate over it:

xs = [(1,2,3,4), (5, 2, 3, 4), (2, 3, 3, 3), (1, 5, 2, 3)]
newList = []
xs.sort()
lastX = None
for x in xs:
  if lastX:
    if lastX[0] == x[0]:
      lastX = None
    else:
      newList.append(lastX)
      lastX = x
if lastX:
  newList.append(lastX)
0
source

Source: https://habr.com/ru/post/1760889/


All Articles