有人可以提供有关如何按特定列表元素查找和分组列表的建议吗?
下面是一个通过比较所有列表元素来查找和分组子列表中相同值的示例...
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']
非常感谢任何帮助或指示...
答案 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)