首页 > 解决方案 > 将列表中每个值的计数减少一些值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"]

标签: pythonlist

解决方案


这是使用的一种方法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']

推荐阅读