簡體   English   中英

如何在清單中計算。 列表混合在Python中

[英]How to count in List. List is mixed in Python

我的清單是L = [[1,1], [2,2], [1,1], 1]

我想在numpy中計算L中的不同元素。 怎么樣??? 計數后答案應為3。

這是一種方法。 訣竅是將可迭代對象轉換為可哈希類型(例如元組)。 然后,您可以轉換為set並計算len

當然,這不會區分列表中的list和tuple元素。 但這可能不適用於您的用例。

from collections import Iterable

L = [[1,1], [2,2], [1,1], 1]

len(set(tuple(i) if isinstance(i, Iterable) else i for i in L))

# 3

如果項目在其類中至少是可排序的,這是一種查找不合理的方法。 由於Python3大多數不允許跨類型比較,因此我們先按類型排序,然后按值排序:

>>> from operator import itemgetter as item_, attrgetter as attr_
>>> from itertools import groupby
>>> 
>>> by_type = groupby(sorted(zip(map(attr_('__qualname__'), map(type, L)), L)), item_(0))
>>> by_type = {k: list(map(item_(0), groupby(map(item_(1), g)))) for k, g in by_type}
>>> by_type
{'int': [1], 'list': [[1, 1], [2, 2]]}
# total number of uniques
>>> sum(map(len, by_type.values()))
3

對於那些不喜歡map這里是使用理解的翻譯:

>>> by_type = groupby(sorted((type(i).__qualname__, i) for i in L), item_(0))
>>> by_type = {k: [gk for gk, gg in groupby(gval for gtp, gval in g)] for k, g in by_type}
>>> by_type
{'int': [1], 'list': [[1, 1], [2, 2]]}

首先對列表的每個元素進行字符串化

然后找到一組字符串化元素的列表

然后得到集合的長度

print(len(set([str(i) for i in L])))

>>> 3

還...您的OP請求“以numpy格式”,由於在數組中不能具有多個數據類型(列表和整數),因此無法顯示。

eta:

從評論中,很好的抓住了保羅·潘澤 這應該修補問題,同時保持簡潔的襯線:

L1 = [[0], np.array([0])]
print (len(set([(str(i)+str(type(i))) for i in L1])))
>>> 2

L2 = [[0, 1], np.array([0, 1])]
print (len(set([(str(i)+str(type(i))) for i in L2])))
>>> 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM