【发布时间】:2015-12-31 07:49:52
【问题描述】:
import string
from collections import namedtuple
from collections import defaultdict
from collections import OrderedDict
matrix_col = {'11234':0, '21234':2, '31223':0, '46541':0, '83432':1, '56443':2, '63324':0, '94334':0, '72443':1}
matrix_col = OrderedDict(sorted(matrix_col.items(), key=lambda t: t[0]))
trans = defaultdict(dict)
trans['11234']['46541'] = 2
trans['11234']['21234'] = 1
trans['11234']['31223'] = 2
trans['11234']['83432'] = 1
trans['21234']['31223'] = 2
trans['21234']['46541'] = 1
trans['21234']['72443'] = 1
trans['21234']['83432'] = 1
trans['56443']['72443'] = 1
trans['56443']['83432'] = 1
for u1, v1 in matrix_col.items():
for u2, v2 in matrix_col.items():
for w1 in trans.keys():
for w2, c in trans[u1].items():
if u1 == str(w1) and u2 == str(w2):
print u1, u2, c
如上所述,我正在尝试根据 matrix_col (OrderedDict) 中元素的排序顺序打印 trans (defaultdict) 的元素并且无法执行那。以下是我无法生成的预期输出:
11234 11234 0
11234 21234 1
11234 31223 2
11234 46541 2
11234 56443 0
11234 63324 0
11234 72443 0
11234 83432 1
11234 94334 0
21234 11234 0
21234 21234 0
21234 31223 2
21234 46541 1
21234 56443 0
21234 63324 0
21234 72443 1
21234 83432 1
21234 94334 0
31223 11234 0
31223 21234 0
31223 31223 0
31223 46541 0
31223 56443 0
31223 63324 0
31223 72443 0
31223 83432 0
31223 94334 0
...
感谢任何帮助。
【问题讨论】:
-
既然您显然在编写 Python 2 代码,我需要指出:
if u1 in trans.keys():是一行糟糕的代码。 Python 2 上的trans.keys()会创建一个新的list键,因此每次测试时您都会制作一个较大的对象,然后线性扫描它以获得命中,而不是直接使用 @987654327 进行O(1)成员资格测试@。同样,.items()的大多数用途可能应该是.iteritems()或.viewitems()直接迭代,而不是让lists 复制它们(纯.keys()/.items()只有在你将在迭代期间改变dict)。
标签: python numpy ordereddictionary defaultdict