2010-11-07 85 views
2

我有了一个地名作为重点和值有字的若干名单,例如,1项外观的字典:词典在Python

{'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']]} 

我如何加入他们都这样我可以得到与每个地方相关的常用词汇吗? 我希望我的输出变得愚蠢和新的作为字典的常用词。

+3

您的列表中包含其他列表,但没有正确包含。 – pyfunc 2010-11-07 20:00:07

+2

举例说明了预期的输出。它有点不清楚你想要什么。 – Ponkadoodle 2010-11-07 20:23:35

+0

您为字典条目显示的值是独立单词和其他单词的子列表的列表,这样做的分隔符在语法上不正确,与您的书面描述不符。除了括号问题,这是错误的,你的描述或价值? – martineau 2010-11-07 22:46:03

回答

2

该函数获取单词列表并返回在所有列表中找到的所有单词。
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 

或巨一行代码:

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

或只是在这个答案的意见建议的方法之一去。

+4

'reduce(set.intersection,map(set,places))' – jfs 2010-11-07 21:00:05

+0

@ J.F。我应该知道有一个比我发布的更简洁的方式。毕竟是Python ... – Ponkadoodle 2010-11-08 00:02:39

+1

'在Python 2.6或更新的版本中设置'set.intersection(* map(set,places))'。 – jfs 2010-11-14 01:13:50

1

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

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

+1

这不适用于嵌套列表。 – 2010-11-07 20:13:04

1

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

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