【问题标题】:Sorting and grouping lists and sub lists with the same values in Python在Python中对具有相同值的列表和子列表进行排序和分组
【发布时间】:2015-07-30 06:27:10
【问题描述】:

我想知道谁能帮我解决这个问题,我感觉如此接近但到目前为止......我似乎无法理解这个问题。

我有一个按列排序的 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

单个列表上的工作示例

使用集合模块中的 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

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

【问题讨论】:

    标签: python list sorting duplicates counter


    【解决方案1】:

    您可以通过字典中的X 值来累积它们,然后将结果排序到列表中。在我的示例中,我使用了 defaultdict,因为我想在字典的项目上调用 append,这使我无需为遇到的每个 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]]]
    

    我知道这与您所采用的路径有点不同,但字典实现了您的基本想法,即“链接”您的 YZ 值到您的 X 值。

    【讨论】:

    • 非常感谢布赖恩,我非常感激!这在 3D CAD 软件中非常有效。认为我需要阅读收藏模块!再次感谢您!
    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2020-12-29
    • 2018-08-30
    • 2017-02-20
    • 2015-05-27
    相关资源
    最近更新 更多