繁体   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