如何在Python中初始化二维数组? [英] How to initialize a two-dimensional array in Python?
问题描述
我开始使用python,并尝试使用一个二维列表,最初我在每个地方都填充了相同的变量.我想到了这个:
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this:
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 = []
它给出了预期的结果,但是感觉像是一种解决方法.有没有更简单/更短/更优雅的方式来做到这一点?
It gives the desired result, but feels like a workaround. Is there an easier/shorter/more elegant way to do this?
推荐答案
Python中经常出现的一种模式是
A pattern that often came up in Python was
bar = []
for item in some_iterable:
bar.append(SOME EXPRESSION)
这有助于激励列表理解的引入,从而将代码段转换为
which helped motivate the introduction of list comprehensions, which convert that snippet to
bar = [SOME EXPRESSION for item in some_iterable]
更短,有时更清晰.通常您会养成识别这些习惯的习惯,并经常用理解代替循环.
which is shorter and sometimes clearer. Usually you get in the habit of recognizing these and often replacing loops with comprehensions.
您的代码两次遵循此模式
Your code follows this pattern twice
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) /
这篇关于如何在Python中初始化二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!