gpt4 book ai didi

python 3嵌套理解

转载 作者:太空宇宙 更新时间:2023-11-04 04:49:18 26 4
gpt4 key购买 nike

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

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

关于python 3嵌套理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48779589/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com