嵌套 dict 推导式

2024-09-30 02:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中

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

我得到了一份口述清单:

^{pr2}$

我只想得到一个扁平的dict,比如:

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

我应该如何更改代码? 注意:我使用的是python2.7。在


Tags: 代码inltfordicttweetstweetword
3条回答

for循环移到dict理解中:

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

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

^{pr2}$
{word: score_tweet(tweet) for tweet in tweets for word in tweet}

你需要一个中间步骤。在

words = []
tweets = ["one two", "three four"]
for tweet in tweets:
    words.extend(tweet.split())
scores = {word: score_tweet(word) for word in words}

相关问题 更多 >

    热门问题