python - 将列表中每个值的计数减少一些值Python
问题描述
我徘徊,有没有办法通过将其计数减少某个数字(1,2,3..10 ...)或将计数除以某个数字来减少列表中每个值的数量。例如:
list = ["one","one","three","three","four","three","four", "four"]
第一种情况的结果(将数字减少每个值 2):
["three", "four"]
第二种情况的结果(除以 2 --> 这很棘手,因为 3/2 是 1.5,但例如将数字四舍五入为 1 ):
["one", "three", "four"]
解决方案
这是使用的一种方法Counter
:
from collections import Counter
from itertools import chain, repeat
l = ["one","one","three","three","four","three","four", "four"]
n = 2
c = Counter(l).items()
list(chain.from_iterable(repeat(k, v-n) for k,v in c))
# ['three', 'four']
对于第二种情况,我们可以通过以下方式进行地板划分n=2
:
list(chain.from_iterable(repeat(k, v//n) for k,v in c))
# ['one', 'three', 'four']
推荐阅读
- flutter - 日文标签无法在 Mapbox 上显示
- google-apps-script - 自动 GMail 分级(谷歌脚本)
- amazon-web-services - API 网关代理与 CDK 中的 lambda 函数集成
- python-3.x - 如何展平包含值和其他列表的列表?
- nuxt.js - 保存 oAuth 用户 - Nuxt auth - github 策略
- parsing - PEGjs 语法星号 (*) 与预期不匹配
- terraform - terraform plan 通知基础设施的变化,但也说没有变化
- java - Android Studio 抛出:启动层 java.lang.module.FindException 初始化时出错:找不到模块 java.se.ee
- marklogic - Marklogic 实体属性与有效掌握的关系
- python - 即使我将 python datetime 对象作为输入,sqlalchemy 中的 DateTime 对象也会返回 null