简体   繁体   中英

Python program to accept a List,and extract all elements whose frequency is greater than K?

Python - How can I write a python program to accept a List, and extract all elements whose frequency is greater than K? Please advise?

Sample I/O:

Input List:

[4, 6, 4, 3, 3, 4, 3, 4, 6, 6]

Input K:

2

Required Output : [4, 3, 6]

Use a list comprehension:

a = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6]
k = 2
out =  [i for i in set(a) if a.count(i) > k]

Use counter in python

list1 = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6]
d = Counter(list1)
new_list = list([item for item in d if d[item] > 1])
print(new_list) #output: [4, 6, 3]

inputs = 0
user_list = []

while inputs < 8:
    user_input = int(input("Enter a number: "))
    user_list.append(user_input)
    inputs += 1

input_list = [4, 6, 4, 3, 3, 4, 6, 6]
input_k = 2

def extract(x, y):
    product = []
    for i in x:
        list_element = i
        if list_element > y:
            product.append(i)
        else:
            break
    product = list(set(product))
    return product

print(extract(user_list, input_k))
print(extract(input_list, input_k))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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