小编laf*_*for的帖子

连接二维数组中的列

我有一个类似于这个字符串的列表列表:

arr = [['a', 'b', 'c'],
       ['X', 'Y', 'Z'],
       ['1', '2', '3'],
      ]
Run Code Online (Sandbox Code Playgroud)

我需要转换为连接的"列"列表,即:

['aX1', 'bY2', 'cZ3']
Run Code Online (Sandbox Code Playgroud)

我提出了将整个阵列顺时针旋转90度的解决方案,然后以相反的顺序连接每行中的所有项目:

[''.join(reversed(row)) for row in zip(*reversed(arr))]
Run Code Online (Sandbox Code Playgroud)

只要每行具有相同数量的项目,这就有效.但是如果不是这样的话怎么办呢.说我有这样的数组:

arr = [['a', 'b', 'c', 'd'],
       ['X', 'Y'],
       ['1', '2', '3'],
      ]
Run Code Online (Sandbox Code Playgroud)

而我的期望是:

['aX1', 'bY2', 'c3', 'd']
Run Code Online (Sandbox Code Playgroud)

在使用上述解决方案之前,我可以使用空字符串项填充较短的行:

max_item_count = max(len(row) for row in arr)
arr = [row + [''] * (max_item_count - len(row)) for row in arr]
Run Code Online (Sandbox Code Playgroud)

但肯定有更好的方法吗?

python python-3.x

1
推荐指数
1
解决办法
90
查看次数

标签 统计

python ×1

python-3.x ×1