Skip to main content
 首页 » 编程设计

python 3嵌套理解

2025年01月19日11kuangbin

是否有一种智能列表/字典理解方式来获得下面的预期输出:

import numpy as np 
freq_mat = np.random.randint(2,size=(4,5)); 
tokens = ['a', 'b', 'c', 'd', 'e']; 
labels = ['X', 'S', 'Y', 'S']; 

freq_mat 的预期输出

array([[1, 0, 0, 1, 1], 
       [0, 0, 0, 0, 1], 
       [1, 0, 1, 1, 0], 
       [0, 1, 0, 0, 0]]) 

应该喜欢以下内容:

[({'a': True, 'b': False, 'c': False, 'd': True, 'e': True}, 'X'), 
 ({'a': False, 'b': False, 'c': False, 'd': False, 'e': True}, 'S'), 
 ({'a': True, 'b': False, 'c': True, 'd': True, 'e': False}, 'Y'), 
 ({'a': False, 'b': True, 'c': False, 'd': False, 'e': False}, 'S')] 

请您参考如下方法:

您可以将该代码折叠为:

代码:

featureset = [ 
    ({key: val > 0 for val in row for key in tokens}, label) 
    for row, label in zip(freq_mat, labels)] 

测试代码:

freq_mat = np.random.randint(2, size=(4, 5)); 
tokens = ['a', 'b', 'c', 'd', 'e']; 
labels = ['X', 'S', 'Y', 'S']; 
 
featureset2 = [] 
for row, label in zip(freq_mat, labels): 
    d = dict() 
    for key in tokens: 
        for val in row: 
            d[key] = val > 0 
    featureset2.append((d, label)) 
 
featureset = [ 
    ({key: val > 0 for val in row for key in tokens}, label) 
    for row, label in zip(freq_mat, labels)] 
 
assert featureset == featureset2