简体   繁体   English

打印一个包含最多 n 个重复元素的列表

[英]Print a list with a max n of repeated elements

To sum up I need to do create a function that receives a list as an input and a number N and returns a new list that contains each repeated element on the maximum of n times总而言之,我需要创建一个 function 接收一个列表作为输入和一个数字 N 并返回一个新列表,其中包含最多 n 次的每个重复元素

Here is an example:这是一个例子:

def reduceList(L,n):
    newList = []
    n = int(input('how many times?'))
    for i in L:
        if i not in L:
            newList.append(i)
    newList.sort()
    return L

lisca = [1, 2, 3, 2, 5, 6, 7, 2, 1, 7, 1, 7]
lisca = reduceList(lisca)
print(lisca)

one solution would be as follows:一种解决方案如下:

def reduceList(oldList: list, numberOfRepeats: int):
    newList = []
    for item in oldList:
        if newList.count(item) < numberOfRepeats:
            newList.append(item)
    newList.sort()
    return newList

good luck!祝你好运!

Using Counter to create a dictonary where the key is an item in list and the value is the occurence, the main wrapper:使用 Counter 创建一个字典,其中键是列表中的项目,值是出现次数,主要包装器:

lisca=  [1, 2, 3, 2, 5, 6, 7, 2, 1, 7, 1, 7]
occurence_dict = Counter(lisca)
Counter({1: 3, 2: 3, 7: 3, 3: 1, 5: 1, 6: 1})
lisca = parse_list(lisca,2)
occurence_dict = Counter(lisca)
Counter({1: 2, 2: 2, 7: 2, 3: 1, 5: 1, 6: 1})

The function code: function代码:

from collections import Counter
def parse_list(L,n):
    result_list = []
    occurence_dict = Counter(L)
    for key, counter in occurence_dict.items():
        if counter <= n:
            result_list.extend([key for i in range(counter)])
        else:
            result_list.extend([key for i in range(n)])
    return result_list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM