sorting a list of tuples

萝らか妹 提交于 2019-12-24 09:58:06

问题


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

Current idea that isn't working:

for (x) in list:
   a,b,c,d=(x)
   if list.count(a)==1:
      newlist.append(x)

回答1:


If you don't want to add any of the tuples that have duplicate a values (as opposed to adding the first occurrence of a given a, but none of the later ones):

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])



回答2:


You could use a set to keep track of the duplicates:

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)



回答3:


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()))

I am using a dictionary to store a values and the tuples that have that a value. The value at that key is a tuple of (count, tuple) where count is the number of times that a has been seen.

At the end, I filter the values dictionary for only those a values where the count is 1, i.e. they are unique. Then I map that list to return only those tuples, since the count value will be 1.

Now, unique_tups is a list of all those tuples with unique a's.

Updated after receiving feedback from commenters, thanks!




回答4:


you could indeed 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)


来源:https://stackoverflow.com/questions/3259159/sorting-a-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!