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

如何编写Python函数实现数组行的指定左移位?

Python列表行元素左移实现方案

可以用列表切片轻松实现这个左移需求,核心思路是把每行需要左移的位数和行的位置对应起来,通过切片拼接完成移位操作。

实现代码

首先将所有目标列表放入一个容器列表,方便批量处理:

list1 = ['0x68', '0x65', '0x6c', '0x6c']
list2 = ['0x20', '0x68', '0x69', '0x74']
list3 = ['0x6c', '0x65', '0x72', '0x68']
list4 = ['0x65', '0x6c', '0x6c', '0x20']

rows = [list1, list2, list3, list4]

然后定义移位函数,跳过第一行,对后续行按索引对应位数左移:

def shift_rows(rows):
    # 从第二行(索引1)开始遍历,左移位数等于当前行的索引值
    for i in range(1, len(rows)):
        shift_count = i
        # 切片拼接实现左移:取后n位 + 取前n位
        rows[i] = rows[i][shift_count:] + rows[i][:shift_count]
    return rows

调用函数并查看结果:

shifted_rows = shift_rows(rows)
for idx, row in enumerate(shifted_rows, 1):
    print(f"list{idx}: {row}")

运行结果

list1: ['0x68', '0x65', '0x6c', '0x6c']
list2: ['0x68', '0x69', '0x74', '0x20']
list3: ['0x72', '0x68', '0x6c', '0x65']
list4: ['0x20', '0x65', '0x6c', '0x6c']

关键逻辑说明

左移n位的核心操作是row[n:] + row[:n]:

  • row[n:]提取列表中从第n个元素到末尾的所有元素
  • row[:n]提取列表中开头到第n个元素之前的所有元素
  • 两者拼接后,就完成了将前n个元素移到列表末尾的左移效果

内容的提问来源于stack exchange,提问作者james.yi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:35:16