排序元组列表 [英] sorting a list of tuples

查看:60
本文介绍了排序元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式为(a,b,c,d)的元组列表,我只想将具有唯一值'a'的那些元组复制到新列表中.我是python的新手.

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.

当前无效的想法

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

推荐答案

如果您想要添加任何具有重复a值的元组(而不是添加第一个元组)给定的a出现了,但以后都没有):

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

这篇关于排序元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆