gpt4 book ai didi

操作同一字典的 Pythonic 方式

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:47 24 4
gpt4 key购买 nike

一个非常天真的问题..我有以下功能:

def vectorize(pos, neg):
vec = {item_id:1 for item_id in pos}
for item_id in neg:
vec[item_id] = 0
return vec

示例:

>>> print vectorize([1, 2] [3, 200, 201, 202])
{1: 1, 2: 1, 3: 0, 200: 0, 201: 0, 202: 0}

我觉得,这在 python 中太冗长了..有没有更 pythonic 的方法来做到这一点...基本上,我返回一个字典,如果它在 pos(列表)中则值为 1,否则为 0?

最佳答案

我不确定这是否更符合 Python 风格……也许效率更高一点?不知道,真的

pos = [1, 2, 3, 4]
neg = [5, 6, 7, 8]

def vectorize(pos, neg):
vec = dict.fromkeys(pos, 1)
vec.update(dict.fromkeys(neg, 0))
return vec

print vectorize(pos, neg)

输出:

{1: 1, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0}

但我也喜欢你的方式...只是在这里提供一个想法。

关于操作同一字典的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27350175/

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