加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 我可以将计数器反转到没有倍数的列表列表吗?

发布时间:2020-12-20 12:00:20 所属栏目:Python 来源:网络整理
导读:使用 Collection Counter, l1 = ['a','b','c','e']l2 = ['a','d']from collections import Counterc1 = Counter(l1)c2 = Counter(l2)# Intersection c1 c2 Counter({'b': 3,'c': 2,'a': 1}) 什么成语可以将Collections Counter分配到列表列表中,每个列表在每
使用 Collection Counter,

l1 = ['a','b','c','e']
l2 = ['a','d']

from collections import Counter

c1 = Counter(l1)
c2 = Counter(l2)

# Intersection 
c1 & c2

>>> Counter({'b': 3,'c': 2,'a': 1})

什么成语可以将Collections Counter分配到列表列表中,每个列表在每个列表中只出现一次?

[['a','c'],['b',['b']]

解决方法

不知道你是否在寻找单线,但这是一个单线:

码:

[sorted(y for y in z if y is not None) 
       for z in it.izip_longest(*[[k] * l for k,l in c.items()])]

怎么样?

这里有两件关键的事情

> [k] * l给出一个计数器键列表,它是计数器值长
> izip_longest()会将列表添加到其他列表中,填充填充为none

测试代码:

from collections import Counter
c = Counter({'b': 3,'a': 1})

import itertools as it
print([sorted(y for y in z if y is not None) 
       for z in it.izip_longest(*[[k] * l for k,l in c.items()])])

结果:

[['a',['b']]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读