【问题标题】:Python: Selecting repeated elements (list in a list) and put it in an array? [duplicate]Python:选择重复的元素(列表中的列表)并将其放入数组中? [复制]
【发布时间】:2020-08-03 08:01:00
【问题描述】:

如何制作:

[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 1], [1, 0, 1], [1, 0, 1]]

这个?

array([[1, 0, 0],
       [1, 0, 1]])

我试过了,但它只适用于 2 个重复的元素。我希望它适用于任意数量的重复元素。

finalRes = []

for i in range(len(resList)-1):
    if resList[i] == resList[i+1]:
        finalRes.append(resList[i])

finalRes --> [[1, 0, 0], [1, 0, 0], [1, 0, 1], [1, 0, 1]]

【问题讨论】:

  • 你想要整个数组中唯一的元素还是连续的?

标签: python for-loop if-statement append repeat


【解决方案1】:

使用itertools.groupby:

from itertools import groupby

lst = [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 1], [1, 0, 1], [1, 0, 1]]

result = [key for key, _ in groupby(lst)]
print(result)

输出

[[1, 0, 0], [1, 0, 1]]

【讨论】:

    【解决方案2】:

    您可以使用numpy.unique 查找数组中的唯一元素。

    用途:

    import numpy as np
    
    arr = [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 1], [1, 0, 1], [1, 0, 1]]
    unique_arr = np.unique(arr, axis=0)
    print(unique_arr)
    

    打印出来:

    [[1 0 0]
     [1 0 1]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-02
      • 2018-11-11
      • 2018-04-29
      • 2019-06-01
      • 2013-12-15
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多