python - 如何在二维列表中同时打印每一行和每一列?
问题描述
我具体想做的是:
二维列表:
l1 = [[2,4,5],
[5,7,5],
[1,9,7]]
我希望输出为:
row = 2,4,5 column = 2,5,1
row = 5,7,5 column = 4,7,9
row = 1,9,7 column = 5,5,7
这就是我所拥有的:
x = -1
for i in range(3):
x+=1
print(l1[i], end="")
print(l1[x][i])
解决方案
行:
rows = l1
Output: [[2, 4, 5], [5, 7, 5], [1, 9, 7]]
科尔斯:
cols = [[row[i] for row in l1] for i in range(col_length)]
Output: [[2, 5, 1], [4, 7, 9], [5, 5, 7]]
或如评论中所述:
cols = list(zip(*rows))
Output: [(2, 5, 1), (4, 7, 9), (5, 5, 7)]
压缩和操作:
>>> for row, col in zip(rows, cols):
... print(str(row), str(col))
...
[2, 4, 5] [2, 5, 1]
[5, 7, 5] [4, 7, 9]
[1, 9, 7] [5, 5, 7]
>>> for row, col in zip(rows, cols):
... print("rows = {} columns = {}".format(",".join(map(str, row)), ",".join(map(str, col))))
...
rows = 2,4,5 columns = 2,5,1
rows = 5,7,5 columns = 4,7,9
rows = 1,9,7 columns = 5,5,7
推荐阅读
- python - dataframe.iloc[:;:] 和 datafrane.iloc[:,:] .values 有什么区别
- scala - 将 Set 转换为 Scala Spark 中的单个对象
- javascript - 无法在 MacOS 10.13.2 上设置 Reaction Commerce
- python - 如何为不泄漏内存的大型生成器编写消费者?
- python - 如何将模块的属性添加到具有自定义行为的类
- azure - 使用 Postman 在 Azure 上发出 500 内部服务器错误 POST 请求
- java - 无法在我的依赖项中实现 'com.firebaseui:firebase-ui-auth:2.3.0'
- python - 如何让 arff.loadarff 与 urllib.request 一起从 URL 读取 arff 文件?
- ruby-on-rails - 基于关联的 Rails
- html - 我的代码中的 CSS 对齐有什么问题