簡體   English   中英

Pythonic方式操縱相同的字典

[英]Pythonic way to manipulate same dictionary

一個非常天真的問題..我有以下功能:

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?

我不是特別相信這是否更加pythonic ...也許更有效率? 不知道,真的

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}

但我也喜歡你的方式......只是在這里提出一個想法。

我可能只是這樣做:

def vectorize(pos, neg):
    vec = {}
    vec.update((item, 1) for item in pos)
    vec.update((item, 0) for item in neg)
    return vec

但是你的代碼也很好。

你可以用

vec = {item_id : 0 if item_id in neg else 1 for item_id in pos}

但請注意,如果neg是列表(而不是集合),則neg item_id in neg將無效。

更新:看到您的預期輸出后。

請注意,上述內容不會為neg項插入0。 如果您也想要,可以使用以下單行。

vec = dict([(item_id, 1) for item_id in pos] + [(item_id, 0) for item_id in neg])

如果你想避免創建兩個臨時列表, itertools.chain可以提供幫助。

from itertools import chain
vec = dict(chain(((item_id, 1) for item_id in pos), ((item_id, 0) for item_id in neg)))

這將是Pythonic,在相對較短的意義上,並最大限度地利用語言的功能:

def vectorize(pos, neg):
    pos_set = set(pos)
    return {item_id: int(item_id in pos_set) for item_id in set(pos+neg)}

print vectorize([1, 2], [3, 200, 201, 202])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM