簡體   English   中英

Python 程序接受一個List,並提取所有頻率大於K的元素?

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

Python - 我如何編寫一個 python 程序來接受一個列表,並提取所有頻率大於 K 的元素? 請指教?

示例 I/O:

輸入列表:

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

輸入 K:

2

需要 Output : [4, 3, 6]

使用列表推導:

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]

在 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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM