[英]python . making matrix with list
I want to make matrix with list我想用列表制作矩阵
What I want to make is this following .我想做的是以下内容。
coll = ["AA","BB","CC","DD"]
What I want to make is this following .我想做的是以下内容。
matrix = [
["AA:AA","AA:BB","AA:CC","AA:DD"],
["BB:AA","BB:BB","BB:CC","BB:DD"],
["CC:AA","CC:BB","CC:CC","CC:DD"],
["DD:AA","DD:BB","DD:CC","DD:DD"],
]
I am newbie in Python ... Could someone give me how to do and with some references or explanation ?我是 Python 新手...有人可以给我一些参考资料或解释吗?
The Pythonic way to implement this is a two-tier list comprehension.实现这一点的 Pythonic 方法是两层列表理解。
coll = ["AA","BB","CC","DD"]
matrix = [
['%s:%s' % (a, b) for b in coll]
for a in coll
]
Another way to put it that might be easier to understand is另一种可能更容易理解的表达方式是
matrix = []
for a in coll:
row = []
for b in coll:
row.append('%s:%s' % (a, b))
matrix.append(row)
but the result will be the same:但结果是一样的:
print(matrix)
[['AA:AA', 'AA:BB', 'AA:CC', 'AA:DD'],
['BB:AA', 'BB:BB', 'BB:CC', 'BB:DD'],
['CC:AA', 'CC:BB', 'CC:CC', 'CC:DD'],
['DD:AA', 'DD:BB', 'DD:CC', 'DD:DD']]
Actually I solved by my *easy and *shy way其实我用我*简单和*害羞的方式解决了
coll = ["AA","BB","CC","DD"]
mat = [[0]*4 for i in range(4)]
i = j =0
for xx in coll :
for yy in coll :
mat[i][j] = xx + ':' + yy
j += 1
i += 1
j = 0
print(mat)
I appreciated with all guys.我很欣赏所有的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.