2010-11-07 166 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' 
>>>