python-3.x - 按嵌套列表上的索引删除

标签 python-3.x list iteration

我有一个嵌套列表:

x = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

我想迭代列表并返回一个新的嵌套列表,每个列表返回时缺少一个值。所以:

new_x = [[2,3,4],[1,3,4],[1,2,4],[1,2,3]]

我有这个:

temp_list = []
y = 0
for i in x:
    temp_list += i.remove(y)
    y+=1
print(x)

但是发生的情况是每次迭代都会删除索引项,因此列表超出范围。

最佳答案

list = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
for count, i in enumerate(list):
    if len(i) > 0:
        del i[count]
print(list)

对于每个子列表,它删除索引等于子列表索引的元素

>>>[[2, 3, 4], [1, 3, 4], [1, 2, 4], [1, 2, 3]]

希望这有帮助!

关于python-3.x - 按嵌套列表上的索引删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346173/

相关文章:

带有多个参数的 Python 打印与打印 fstring

python - 如何在QMainWindow中显示对象信息

python - 如何在 Python 中使用 Bokeh 查看 Holoviews 的选项

python - 需要在 Python 中对长的、格式奇怪的数据集取平均值

python - 如何使用 iterrows 和 iteritems 更快地运行 pandas for 循环

c++ - 如何以相反的顺序将整个 vector 复制到队列中?

python - 为什么我的计算机内置计算器最多只能计算 101 个阶乘,但我的 python 阶乘脚本可以计算得更高?

r - 分析列表中的数据框并绑定(bind)结果

list - 尾递归List.map

Haskell迭代器: simple worked example of stripping trailing whitespace