通过特定的相同列表值在Python中对列表进行分组

时间:2015-08-10 16:18:26

标签: python list sorting tuples

有人可以提供有关如何按特定列表元素查找和分组列表的建议吗?

下面是一个通过比较所有列表元素来查找和分组子列表中相同值的示例...

在列表中查找和分组相同值的工作示例:

L = #List of Vectors

# Example L[0] = [8.999999590709139, 164.00000059986633, 152.00000160567942]

d = defaultdict(list) # Group by same Vectors

for item in L:
    d[tuple(item)].append(item)

sv = sorted(d[x] for x in d)

print "No of same values found =”, len(sv) 

上面的工作示例考虑了列表中的所有项目以进行比较,但是如何考虑仅通过列表的前三项来查找和分组相同的项目,同时保持列表的完整性?

# Example L2[0] = [8.999999590709139, 164.00000059986633, 152.00000160567942, "Q","W","E","R","T","Y","3.14"]

# Example L2[1] = [8.999999590709139, 164.00000059986633, 152.00000160567942, "A","S","D","F","G","H","J"]

# len(L2[0]) = 10

# Find and group lists with same L2[i][0], L2[i][1], L2[i][2] values...

# Desired output - sortedlist = [[[1,2,3,"a","b","c"],[1,2,3,"d","e","f"]],[[3,4,5,"a","b","c"],[3,4,5,"d","e","f"]]]

#print sortedlist returns [[[1, 2, 3, 'a', 'b', 'c'], [1, 2, 3, 'd', 'e', 'f']], [[3, 4, 5, 'a', 'b', 'c'], [3, 4, 5, 'd', 'e', 'f']]]

#print sortedlist[1] returns [[3, 4, 5, 'a', 'b', 'c'], [3, 4, 5, 'd', 'e', 'f']]

#print sortedlist returns [1][2] [3, 4, 5, 'a', 'b', 'c']

非常感谢任何帮助或指示...

1 个答案:

答案 0 :(得分:0)

谢谢jzk2 ......

 from collections import defaultdict

 d = defaultdict(list)

for item in L:
    d[tuple(item[:3])].append(item)

sortedL = sorted(d[x] for x in d)