gpt4 book ai didi

Python:列表中的最小数字,包括重复数字

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:24 24 4
gpt4 key购买 nike

对 python 有点陌生,我很难想出解决这个问题的方法。

假设我有一个列表 A,假设我想返回一个至少包含三个最小值(包括重复值)的列表 B。我将如何为此编写逻辑?对于如何将这种想法转化为代码,我有点不知所措。

例子:

    A = [1,2,3,4,4]
b = [1,2,3]

A = [1,2,3,3,4]
B = [1,2,3,3]

A = [1,1,2,2,3]
B = [1,1,2,2]

A = [1,1,2,3]
B = [1,1,2]

最佳答案

你可以使用heapq模块:

import heapq

def nsmallestwithrepeats(A, n=3):
b = heapq.nsmallest(n, A)
try:
b = set(b)
except TypeError:
pass
return [a for a in A if a in b]

for A in [1,2,3,4,4], [1,2,3,3,4], [1,1,2,2,3], [1,1,2,3]:
print(nsmallestwithrepeats(A))

输出:

[1, 2, 3]
[1, 2, 3, 3]
[1, 1, 2, 2]
[1, 1, 2]

正如@Mathieu Borderé 指出的那样,简单地与 b 的最大元素进行比较可能更有效,而不是形成一个集合:

def nsmallestwithrepeats(A, n=3):
b = heapq.nsmallest(n, A)
return [a for a in A if a <= b[-1]]

关于Python:列表中的最小数字,包括重复数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43385672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com