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

如何循环将列表首尾元素求和直至长度为2并生成百分比

自定义百分比生成实现

需求说明

需要从数字列表生成特殊格式的百分比:重复将列表的首个元素与末尾元素相加,替换这两个元素为相加结果,直到列表长度变为2,最终将两个数字拼接为%XY格式的字符串。

示例过程

# 初始列表
num_list = [1, 1, 2, 1, 1, 1, 1, 1, 1, 1]
# 第一次合并首尾:1+1=2,1+1=2,保留中间元素得到新列表
num_list = [2, 2, 3, 2, 2]
# 第二次合并首尾:2+2=4,2+2=4,保留中间元素得到新列表
num_list = [4, 4, 3]
# 第三次合并首尾:4+3=7,保留中间元素得到最终列表
num_list = [7, 4]

# 生成百分比字符串
percentage = f"%{num_list[0]}{num_list[1]}"
# 输出结果:%74

代码实现

def generate_custom_percent(num_list):
    current_list = num_list.copy()
    # 循环处理直到列表长度为2
    while len(current_list) > 2:
        # 计算首尾元素的和
        sum_val = current_list[0] + current_list[-1]
        # 移除首尾元素
        current_list.pop(0)
        current_list.pop(-1)
        # 将和插入列表头部,和示例步骤逻辑对齐
        current_list.insert(0, sum_val)
    # 拼接成目标格式
    return f"%{current_list[0]}{current_list[1]}"

# 测试示例
test_list = [1, 1, 2, 1, 1, 1, 1, 1, 1, 1]
print(generate_custom_percent(test_list))  # 输出:%74

代码说明

  • 用while循环持续处理列表,直到长度满足要求
  • 每次循环完成首尾元素求和、移除首尾、插入求和结果的操作,和示例步骤完全匹配
  • 最后通过f-string直接拼接出要求的百分比格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:18:25