对 Python 中具有相同值的列表和子列表进行排序和分组

Sorting and grouping lists and sub lists with the same values in Python

我想知道任何人都可以帮助我解决这个问题,到目前为止我感觉很接近....我似乎无法理解这个问题。

我有一个要按列排序的 3D 向量 (X,Y,Z) 列表 - 许多 X 值是相同的。

# Example list (L)

L = [1,7,9], [2,4,9], [2,0,10], [1,12,9], [9,9,1], [4,6,2], [7,6,2], [4,12,6], [5,7,1]

# Desired result
R = [[1,7,9], [1,12,9]], [[2,4,9], [2,0,10]],[[4,6,2], [4,12,6]], [5,7,1], [7,6,2], [9,9,1]

# Example calling individual columns (real values expected to be in the 10's)

R[0] = [[1,7,9], [1,12,9]] # A column 2 high
R[3] = [5,7,1] # A column 1 high

单个列表的工作示例

使用 collections 模块中的 Counter 函数并在此得到一些非常感谢的帮助,以下代码可以对单个列表进行排序:

 from collections import Counter

 N = [2,5,7,9,2,8,5,2,7,9]
 C = Counter(N)

 print [ [k,]*v for k,v in C.items()]
 # Returns [[8], [9, 9], [2, 2, 2], [5, 5], [7, 7]]

我尝试将 Y 和 Z 值链接回新分组的 X 向量,但是我 运行 遇到了索引问题,因为 X 列表的索引发生了变化。

任何帮助将不胜感激,到目前为止这是我的尝试和我正在探索的方向......(将值传递给函数)

from collections import Counter

N = [1,7,9], [2,4,9], [2,0,10], [1,12,9], [9,9,1], [4,6,2], [7,6,2], [4,12,6], [5,7,1]


def compareXvalues(VectorList):
    global Grouped_X_Vectors

    Xvectors = []
    for i in xrange (len(VectorList)):
       Xvectors.append(VectorList[i][0])

    C = Counter(Xvectors)
    Grouped_X_Vectors = [ [k,]*v for k,v in C.items()]

    for i in xrange (len(Grouped_X_Vectors)):
        #print Grouped_X_Vectors[i]
        pass

print N

compareXvalues(N)
print Grouped_X_Vectors

任何反馈或帮助将不胜感激,我的大脑被炸了。

您可以通过字典中的 X 值累积它们,然后将结果排序到列表中。在我的示例中,我使用 defaultdict 因为我想对字典的项目调用追加,这使我无需为遇到的每个 X 值初始化列表。

>>> from collections import defaultdict
>>> L = [[1,7,9], [2,4,9], [2,0,10], [1,12,9], [9,9,1], [4,6,2], [7,6,2], [4,12,6], [5,7,1]]
>>> d = defaultdict(list)
>>> for item in L:
        d[item[0]].append(item)

>>> R = sorted(d[x] for x in d)
>>> R
[[[1, 7, 9], [1, 12, 9]], [[2, 4, 9], [2, 0, 10]], [[4, 6, 2], [4, 12, 6]], [[5, 7, 1]], [[7, 6, 2]], [[9, 9, 1]]]

我知道这与你走的路有点不同,但字典满足了你对 "linking" 你的 YZ 价值观的基本想法 X值。