Python 中的字典

发布于 2024-09-30 16:23:09 字数 358 浏览 3 评论 0原文

我有一本字典,它以地名作为键,作为值,它有多个单词列表,例如,1 个条目看起来像:

{'myPlaceName': [u'silly', u'i', u'wish!', u'lol', [u'the', u'lotto'], [, u'me', u'a', u'baby?'], [u'new', u'have', u'new', u'silly', u'new', u'today,', u'cant', u'tell', u'yet,', u'but', u'all', u'guesses', u'silly']]}

如何将它们全部连接起来,以便获得与每个地点相关的常用单词? 我希望我的输出像字典中的常用词一样变得愚蠢和新颖。

I have a dictionary that has a place name as a key and as the value it has several lists of words, eg, 1 entry looks like:

{'myPlaceName': [u'silly', u'i', u'wish!', u'lol', [u'the', u'lotto'], [, u'me', u'a', u'baby?'], [u'new', u'have', u'new', u'silly', u'new', u'today,', u'cant', u'tell', u'yet,', u'but', u'all', u'guesses', u'silly']]}

How can I join them all so I can get the common words associated with each place?
I would like my output to get silly and new as the common words for the dictionary.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月隐月明月朦胧 2024-10-07 16:23:09

此函数获取单词列表的列表,并返回在所有列表中找到的所有单词。
例如 get_common_words([['hi', 'hello'], ['bye', 'hi']]) 返回 ['hi']

def get_common_words(places):
    common_words = []
    for word in places[0]:
        is_common = all(word in place for place in places[1:]) #check to see that this word is in all places
        if is_common:
            common_words.append(word)
    return common_words

或巨大的一 - liner:

get_common_words = lambda places: [word for word in places[0] if all(word in place for place in places[1:])]

或者只是采用此答案的评论中建议的方法之一。

This function takes a list of a list of words, and returns all words that are found in all the lists.
eg get_common_words([['hi', 'hello'], ['bye', 'hi']]) returns ['hi']

def get_common_words(places):
    common_words = []
    for word in places[0]:
        is_common = all(word in place for place in places[1:]) #check to see that this word is in all places
        if is_common:
            common_words.append(word)
    return common_words

or the giant one-liner:

get_common_words = lambda places: [word for word in places[0] if all(word in place for place in places[1:])]

or just go with one of the methods suggested in the comments of this answer.

苍景流年 2024-10-07 16:23:09

print ', '.join(dictname['myPlaceName'])

这将创建列表中所有条目的逗号分隔列表。将 dictname 替换为您的字典名称。

print ', '.join(dictname['myPlaceName'])

This will create a comma-separated list of all the entries in the list. Replace dictname with the name of your dict.

初心未许 2024-10-07 16:23:09

如果它是仅包含单词的列表,请使用连接。

>>> k = [u'silly', u'i', u'wish!', u'lol']
>>> " ".join(k)
u'silly i wish! lol'
>>> 

If it s a list containing only words, use join.

>>> k = [u'silly', u'i', u'wish!', u'lol']
>>> " ".join(k)
u'silly i wish! lol'
>>> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文