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

如何用Python实现列表首尾交替取元素打印输出

for循环实现列表前后交替取元素逻辑

核心思路

  • 初始化left指针指向列表起始索引(值为0),right指针指向列表末尾索引(值为len(列表)-1)
  • 循环次数设置为列表长度向上取整的一半,保证所有元素都被抓取,不会出现无效循环
  • 每次循环先取左指针对应元素加入结果,左指针右移1位
  • 新增指针重合判断:如果移动后左指针仍小于等于右指针,再取右指针对应元素加入结果,右指针左移1位,避免奇数长度列表的中间元素被重复添加

Python实现代码

def alternate_fetch(input_list):
    result = []
    list_len = len(input_list)
    left_idx = 0
    right_idx = list_len - 1
    # 控制循环次数
    for _ in range((list_len + 1) // 2):
        # 先取前端元素
        result.append(input_list[left_idx])
        left_idx += 1
        # 避免重复添加奇数长度列表的中间元素
        if left_idx <= right_idx:
            result.append(input_list[right_idx])
            right_idx -= 1
    return result

# 测试调用
test_list = [1,2,3,4,5,6,7,8]
print(alternate_fetch(test_list))

输出结果

  • 偶数长度输入[1,2,3,4,5,6,7,8]输出:[1, 8, 2, 7, 3, 6, 4, 5]
  • 奇数长度输入[1,2,3,4,5,6,7]输出:[1, 7, 2, 6, 3, 5, 4],和你给出的示例输出逻辑完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 14:06:05