我代表a Matrix by a dictionary并假设我有一个字典,键是行索引,我怎么能把它(就地看起来很棘手)转换成字典,键是列索引?< / p>
这是我的尝试:
int
但我正在寻找更优雅和Pythonic的东西。这里by_row = {}
N = 3
M = 5
for i in range(1, N):
row = []
for j in range(1, M):
row.append(j)
by_row[i] = row
print by_row
by_column = {}
for i in range(1, M):
col = []
for j in range(1, N):
col.append(by_row[j][i - 1])
by_column[i] = col
print by_column
将行索引作为键,而my_dict_1
将列索引作为键。输出:
my_dict_2
答案 0 :(得分:3)
使用enumerate()
function对列进行编号,并按排序顺序迭代键:
by_column = {}
for rownum, row in sorted(by_row.iteritems()):
for colnum, value in enumerate(row, 1):
by_column.setdefault(colnum, []).append(value)
这假定您的字典中存在所有行号,并且所有行的长度相等。
演示:
>>> N, M = 2, 4 # 2 rows, each 4 columns
>>> by_row = {r: range(1, M + 1) for r in range(1, N + 1)}
>>> by_row
{1: [1, 2, 3, 4], 2: [1, 2, 3, 4]}
>>> by_column = {}
>>> for rownum, row in sorted(by_row.iteritems()):
... for colnum, value in enumerate(row, 1):
... by_column.setdefault(colnum, []).append(value)
...
>>> by_column
{1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4]}
答案 1 :(得分:2)
这是一种超级pythonic方式:
>>> by_row = {1: [1, 2, 3, 4], 2: [1, 2, 3, 4]}
>>> by_column = {n+1:[row[n] for row in by_row.values()] for n in range(len(by_row[1]))}
>>> by_column
{1: [1, 1], 2: [2, 2], 3: [3, 3], 4: [4, 4]}