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[:] for x in [[foo] * 10] * 10] # for immutable foo!
下面是一些python3计时,用于小型和大型列表
$python3 -m timeit '[x[:] for x in [[1] * 10] * 10]'
1000000 loops, best of 3: 1.55 usec per loop
$ python3 -m timeit '[[1 for i in range(10)] for j in range(10)]'
100000 loops, best of 3: 6.44 usec per loop
$ python3 -m timeit '[x[:] for x in [[1] * 1000] * 1000]'
100 loops, best of 3: 5.5 msec per loop
$ python3 -m timeit '[[1 for i in range(1000)] for j in range(1000)]'
10 loops, best of 3: 27 msec per loop
from random import randint
l = []
for i in range(10):
k=[]
for j in range(10):
a= randint(1,100)
k.append(a)
l.append(k)
print(l)
print(max(l[2]))
b = []
for i in range(10):
a = l[i][5]
b.append(a)
print(min(b))
x = 0
mat1 = []
for i in range(3):
mat1.append(x)
x+=1
print(mat1)
x=0
mat2 = []
for i in range(3):
tmp = []
for j in range(4):
tmp.append(x)
x+=1
mat2.append(tmp)
print(mat2)
x=0
mat3 = []
for i in range(3):
tmp = []
for j in range(4):
tmp2 = []
for k in range(5):
tmp2.append(x)
x+=1
tmp.append(tmp2)
mat3.append(tmp)
print(mat3)
N=7
F=2
#INITIALIZATION of 7 x 2 array with deafult value as 0
ar=[[0]*F for x in range(N)]
#RECEIVING NEW VALUES TO THE INITIALIZED ARRAY
for i in range(N):
for j in range(F):
ar[i][j]=int(input())
print(ar)
[x]*col——>被求值的最终表达式
对于——>中的x, x将是迭代器 提供的值
[b for b in range(row)]]——>迭代器
[b for b in range(row)]]这将计算为[0,1,2,3,4],因为row=5
现在简化为
[[x]*col for x in [0,1,2,3,4]]
这将计算为
[[0]*5 for x in[0,1,2,3,4]]——> with x=0第一次迭代 .
[[1]*5 for x in[0,1,2,3,4]]——> with x=1第二次迭代 .
[[2]*5 for x in[0,1,2,3,4]]——> with x=2第三次迭代 .
[[3]*5 for x in[0,1,2,3,4]]——> with x=3第4次迭代 .
[[4] * 5 x[0, 1, 2, 3, 4]]——> x = 4 5迭代< br > < / p >