如何在Python中更改嵌套列表的“列”的值?

jqjz2hbq  于 2023-05-27  发布在  Python
关注(0)|答案(2)|浏览(108)

在python3中,我有一个嵌套列表

my_list= [
   [2,2,2,2],
   [3,3,3,3],
   [4,4,4,4]
]

我想把第二列的所有值都改成0,得到

my_list= [
   [2,0,2,2],
   [3,0,3,3],
   [4,0,4,4]
]

现在我能做的是

for i in range(len(my_list)):
    my_list[i][1] = 0

但它看起来不太“pythonic”,对吗?有没有一种更聪明的方法,不用使用数组的长度?
在Numpy中,我可以使用my_list[:,2]=0

kqlmhetl

kqlmhetl1#

一个更pythonic的方法是:

In [9]: for inner_list in my_list:
   ...:     inner_list[1] = 0
   ...:     

In [10]: my_list
Out[10]: [[2, 0, 2, 2], [3, 0, 3, 3], [4, 0, 4, 4]]

在Python中,当循环遍历列表或集合时,不需要使用range(len(my_list))for循环知道何时停止。

pcrecxhr

pcrecxhr2#

真有趣一个更通用的解决方案在这里似乎是有用的。如果你想用另一列替换那一列...那更像是:

def replaceColumn(listOfLists, n, column):
    ''' Replace the "n"th column of the list of lists "table" source '''
    # Rotate the table...
    t = list(zip(*listOfLists))
    # Replace the (now) row
    t[n] = column
    # Rotate and return the table...
    return list(zip(*t))

那么解决方案更像是:

replaceColumns(my_list, [0]*len(my_list), 1)

但有一个副作用:行以元组结束!

相关问题