python - 更改列表中的最后一个元素
问题描述
我正在尝试反转列表列表,以便存储在源列表中索引处的值成为新列表中的索引,原始索引现在将成为存储值。
例如,列表 [0,2,4,3,1] 之一将变为 [0,4,1,3,2]。
但是,我不知道如何修改列表中的最后一个元素。这是我到目前为止所拥有的:
def invertLists(Lists):
invLists = Lists
testIndex = 2
print("List before: ", Lists[testIndex], "... length: ", len(Lists[testIndex]), '\n')
for i in range(1, len(Lists)):
for j in range(1, len(Lists[i])):
newIndex = Lists[i][j]
if(newIndex == len(Lists[i])):
newIndex = -1
else:
invLists[i][newIndex] = j
if i == testIndex:
print("Insert ", j, " at index ", newIndex)
print("List so far: ", invLists[i], '\n')
return invLists
当列表 = [[], [0, 1, 4, 3, 2], [0, 2, 4, 3, 1], [0, 3, 2, 1, 4], [0, 1, 4, 3, 2]],输出如下:
List before: [0, 2, 4, 3, 1] ... length: 5
Insert 1 at index 2
List so far: [0, 2, 1, 3, 1]
Insert 2 at index 1 ##(should be index 4)##
List so far: [0, 2, 1, 3, 1]
Insert 3 at index 3
List so far: [0, 2, 1, 3, 1]
Insert 4 at index 1
List so far: [0, 4, 1, 3, 1]
(Every list):
[[], [0, 1, 4, 3, 2], [0, 4, 1, 3, 1], [0, 3, 2, 1, 4], [0, 1, 4, 3, 2]]
需要注意的一点是 2 插入到 invLists[1] 而不是 invLists[4]。据我了解,使用 -1 作为索引应该返回列表中的最后一项,所以我不明白为什么这里不这样做。排除 newIndex 设置为 -1 的条件语句会产生相同的结果。
解决方案
问题出在您的循环范围内:
for i in range(1, len(Lists)):
for j in range(1, len(Lists[i])):
Python 结构是零索引的。典型的迭代是
for i in range(len(Lists)):
或者
for idx, elem in enumerate(Lists):
您的关键问题是,对于长度为 N 的循环,您只处理N-1
元素。
对于任何此类列表,这是一个简单得多的转换,my_list
:
[my_list.index(i) for i in range(len(my_list))]
推荐阅读
- powershell - 如何只返回一个数据库的兼容级别?
- ruby-on-rails - 设计引导视图错误渲染:找不到类型为“text/css”的文件“devise_bootstrap_views”
- r - RStudio 全局环境不反映对 data.table 的就地更改
- system-verilog - 在系统verilog中生成块
- python - 如何使用 python 和 TextBlob 在我的 nltk 语料库中获取拼写错误的单词列表
- sql-server-2012 - 使用存储过程更新复选框时仅发送一次电子邮件
- python - 如何在 python 中比较和打印二维列表中的元素?
- python - Pytest:如何从测试方法外部访问命令行参数
- java - Spring安全表单操作登录不起作用
- c++ - unique_ptr 参数类型的模板参数推导指南?