我有不同的名單在python:這個詞出現在多少個列表中?
list1 = [hello,there,hi]
list2 = [my,name,hello]
我需要的鍵是一個單詞出現在列表中的號碼字典所以我的答案看起來像 {2:你好,1:喜....}
我是新來的蟒蛇,我不知道如何做到這一點。
我有不同的名單在python:這個詞出現在多少個列表中?
list1 = [hello,there,hi]
list2 = [my,name,hello]
我需要的鍵是一個單詞出現在列表中的號碼字典所以我的答案看起來像 {2:你好,1:喜....}
我是新來的蟒蛇,我不知道如何做到這一點。
您需要使用字典來存儲鍵值結果。
下面是一些可以幫助您入門的代碼,但您必須修改爲您的確切解決方案。
#!/usr/bin/python
list1 = ["hello","there","hi"]
list2 = ["my","name","hello"]
result = dict()
for word in list1:
if word in result.keys():
result[word] = result[word] + 1
else:
result[word] = 1
for word in list2:
if word in result.keys():
result[word] = result[word] + 1
else:
result[word] = 1
print result
的模塊的集合,而不是免費編寫代碼。告訴方式做。因爲OP需要付出努力。那麼我們可以幫助 – 2014-09-24 05:57:32
雖然我明白你的意思,但有時候看到代碼會推動你。然後你會查看它,解析它,理解它。這有助於我學習經驗。 – Alex 2014-09-24 05:59:54
我很抱歉,我想我應該更清楚。我基本上有一個列表清單。每個列表包含不同的單詞。對於每個列表中的每個單詞,我需要知道它出現了多少個不同的列表。我這樣做是爲了找到這個詞的逆文檔頻率。 – user2731223 2014-09-24 06:16:17
作爲第一步,使像這樣
反向辭典初始化
words_count = {}
,然後字的每個列表不喜歡這樣
for word in list_of_words:
if not word in words_count:
words_count[word] = 1
else:
words_count[word] += 1
再反向words_count像所以:
inv_words_count = {v: k for k, v in words_count.items()}
inv_words_count是所期望的結果
如下所示我稍微修改您的輸入列表(列表1 &列表2):
list1 = ['hello,there,hi'] # Added quotes as it is a string
list2 = ['my,name,hello']
這裏是邏輯:
list1 = list1[0].split(',')
list2 = list2[0].split(',')
list_final = list1 + list2
dict_final = {}
for item in list_final:
if item in dict_final.keys():
dict_final.update({item:(dict_final.get(item) + 1)})
else:
dict_final.update({item:1})
希望它將如你所期望的那樣工作:)
你試過了什麼?並請看看[我如何問一個好問題](http://stackoverflow.com/help/how-to-ask)。 – user1251007 2014-09-24 05:52:11
**注意** 1.字典的鍵是唯一的2. Python中的字符串總是被引用3.如果需要使用數字後綴命名列表,最好創建列表列表。一旦你完成了這個任務,請檢查Python庫,一個名爲Counter – Abhijit 2014-09-24 05:53:30