You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表按百分比筛选元素:求最高值及75%以上元素的实现问题

问题:从列表中筛选符合百分比条件的对象

现有列表示例:

PD = ['cell-phone:', '76%', '65%', 'bottle:', '89%', '48%', 'person:', '78%', 'mouse:', '44%']

该列表包含cell-phone、bottle、person、mouse共4个对象,每个对象后跟随若干百分比数值。需求如下:

  • 找出百分比最高的对象(示例中为bottle,对应89%)
  • 找出所有存在高于75%百分比数值的对象(示例中为cell-phone和person)
  • 最终合并去重后输出列表:[bottle, cell-phone, person]

我已编写的代码仅能找出每个对象的最高百分比,缺少筛选75%以上元素的功能,代码如下:

PD= ['cell-phone:', '0', '45%', '52%', '53%', '56%', '63%', '61%', '65%', 'bottle:', 
'46%', '62%', '58%', '51%', '50%',
 '48%', 'person:', '47%', 'mouse:', '44%']

# remove colons, percentages, etc
clean_pd = [x.translate({ord(c): None for c in ':%'}) for x in PD]

# convert number strings to integers
convert_to_numbers_pd = [int(x) if x.isnumeric() else x for x in clean_pd]

pd_dict = dict()
pd_key = None

# convert PD data to a dict
for x in convert_to_numbers_pd:
    if isinstance(x, (int,)):
        pd_dict[pd_key].append(x)
    if isinstance(x, (str,)):
        pd_key = x
        pd_dict[pd_key] = list()

# get the max value of each key
for k,v in pd_dict.items():
    print(f"{k}: {max(v)}")

完善后的代码

PD= ['cell-phone:', '0', '45%', '52%', '53%', '56%', '63%', '61%', '65%', 'bottle:', 
'46%', '62%', '58%', '51%', '50%',
 '48%', 'person:', '47%', 'mouse:', '44%']

# 清理并转换数据
clean_pd = [x.translate({ord(c): None for c in ':%'}) for x in PD]
convert_to_numbers_pd = [int(x) if x.isnumeric() else x for x in clean_pd]

# 构建对象-百分比列表的字典
pd_dict = dict()
pd_key = None
for x in convert_to_numbers_pd:
    if isinstance(x, int):
        pd_dict[pd_key].append(x)
    else:
        pd_key = x
        pd_dict[pd_key] = list()

# 1. 找出百分比最高的对象
max_obj = max(pd_dict.items(), key=lambda item: max(item[1]) if item[1] else 0)[0]

# 2. 找出所有存在高于75%数值的对象
above_75_objs = [key for key, values in pd_dict.items() if any(v > 75 for v in values)]

# 合并去重并整理结果
result = list({max_obj} | set(above_75_objs))
# 可选:如果需要保持示例中的顺序(最高对象在前,其余按原列表顺序)
# ordered_objs = [obj for obj in pd_dict.keys() if obj in {max_obj} | set(above_75_objs)]
# ordered_objs.remove(max_obj)
# result = [max_obj] + ordered_objs

print(result)

代码说明

  1. 数据处理部分:保留原有清理和转换逻辑,确保对象名和百分比数值正确分离。
  2. 找出最高百分比对象:用max()函数结合lambda表达式,以每个对象的最高百分比为比较依据,直接获取对应对象名。
  3. 筛选75%以上的对象:通过列表推导式和any()函数,检查每个对象的百分比列表是否存在大于75的数值,收集符合条件的对象名。
  4. 合并结果:用集合去重(避免最高对象同时属于75%以上列表时重复),再转为列表;如果需要特定顺序,可使用注释中的代码调整。

内容的提问来源于stack exchange,提问作者kabloeyyy23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:33:16