简体   繁体   English

如何在清单中计算。 列表混合在Python中

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

My list is L = [[1,1], [2,2], [1,1], 1] 我的清单是L = [[1,1], [2,2], [1,1], 1]

I want to count distinct elements in L in numpy. 我想在numpy中计算L中的不同元素。 How??? 怎么样??? Answer should be 3 after counting. 计数后答案应为3。

Here's one way. 这是一种方法。 The trick is to convert iterables to hashable types (eg tuples). 诀窍是将可迭代对象转换为可哈希类型(例如元组)。 You can then convert to a set and calculate len . 然后,您可以转换为set并计算len

What this won't do, of course, is differentiate between list and tuple elements in your list. 当然,这不会区分列表中的list和tuple元素。 But this may not be applicable in your use case. 但这可能不适用于您的用例。

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

Here is a way to find unqiues if items are at least sortable within their class. 如果项目在其类中至少是可排序的,这是一种查找不合理的方法。 As Python3 mostly does not allow across type comparisons we sort by type first and then by value: 由于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

For those who don't like map here is a translation using comprehensions: 对于那些不喜欢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]]}

first stringify each element of list 首先对列表的每个元素进行字符串化

then find set of list of stringified elements 然后找到一组字符串化元素的列表

then get length of set 然后得到集合的长度

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

>>> 3

also... your OP requested "in numpy" which presents impossibility as you can't have multiple data types in an array (lists and ints). 还...您的OP请求“以numpy格式”,由于在数组中不能具有多个数据类型(列表和整数),因此无法显示。

eta: eta:

from comments, nice catch Paul Panzer; 从评论中,很好的抓住了保罗·潘泽 this should patch the issue while remaining concise one liner: 这应该修补问题,同时保持简洁的衬线:

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