我开始使用python,我尝试使用一个二维列表,我开始在每个地方都用相同的变量填充。我想到了这个:

def initialize_twodlist(foo):
    twod_list = []
    new = []
    for i in range (0, 10):
        for j in range (0, 10):
            new.append(foo)
        twod_list.append(new)
        new = []

它给出了预期的结果,但感觉像是一种变通方法。有更简单/更短/更优雅的方法吗?


当前回答

代码:

num_rows, num_cols = 4, 2
initial_val = 0
matrix = [[initial_val] * num_cols for _ in range(num_rows)]
print(matrix) 
# [[0, 0], [0, 0], [0, 0], [0, 0]]

Initial_val必须是不可变的。

其他回答

一个空的2D矩阵可以用以下方式初始化:

temp = [[], []]

Python中经常出现的一个模式是

bar = []
for item in some_iterable:
    bar.append(SOME EXPRESSION)

这有助于推动列表推导式的引入,它将代码片段转换为

bar = [SOME_EXPRESSION for item in some_iterable]

这样更简短,有时也更清楚。通常,您会养成识别这些循环的习惯,并经常用推导式替换循环。

您的代码遵循此模式两次

twod_list = []                                       \                      
for i in range (0, 10):                               \
    new = []                  \ can be replaced        } this too
    for j in range (0, 10):    } with a list          /
        new.append(foo)       / comprehension        /
    twod_list.append(new)                           /

你可以使用列表推导式:

x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of 'foo' (which can depend on i and j if you want)

在Python中初始化一个二维数组:

a = [[0 for x in range(columns)] for y in range(rows)]

初始化一个大小为m X n的二维矩阵,取值为0

m,n = map(int,input().split())
l = [[0 for i in range(m)] for j in range(n)]
print(l)