繁体   English   中英

嵌套字典理解

[英]Nested dict comprehension

在以下代码中,

[{word: score_tweet(tweet) for word in tweet} for tweet in tweets]

我得到的字典列表:

[{u'soad': 0.0, u'<3': 0.0}, {u'outros': 0.0, u'acredita': 0.0}]

我只想获得一个简单的字典,例如:

{u'soad': 0.0, u'<3': 0.0, u'outros': 0.0, u'acredita': 0.0}

我应该如何更改我的代码? 注意:我正在使用Python 2.7。

{word: score_tweet(tweet) for tweet in tweets for word in tweet}

for循环移至dict理解中:

{word: score_tweet(tweet) for tweet in tweets for word in tweet}

请记住,一行中的两个for循环很难阅读。 我会做这样的事情:

scores = {}

for tweet in tweets:
    tweet_score = score_tweet(tweet)

    for word in tweet:
        scores[word] = tweet_score

您需要一个中间步骤。

words = []
tweets = ["one two", "three four"]
for tweet in tweets:
    words.extend(tweet.split())
scores = {word: score_tweet(word) for word in words}
"""
[{u'soad': 0.0, u'<3': 0.0}, {u'outros': 0.0, u'acredita': 0.0}] 
->
{u'soad': 0.0, u'<3': 0.0, u'outros': 0.0, u'acredita': 0.0}
"""
tweets_merged = {}
tweets = [{u'soad': 0.0, u'<3': 0.0}, {u'outros': 0.0, u'acredita': 0.0}]
for tweet in tweets:    
    tweets_merged = dict(tweets_merged.items() + tweet.items())
print tweets_merged

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM