Python 在列表中查找事件
我试图计算列表中的重复项,我编写了这段代码,但它似乎不起作用。有人知道怎么修吗?我避免使用图书馆Python 在列表中查找事件,python,python-3.x,list,dictionary,duplicates,Python,Python 3.x,List,Dictionary,Duplicates,我试图计算列表中的重复项,我编写了这段代码,但它似乎不起作用。有人知道怎么修吗?我避免使用图书馆 string = "btu got punished by btu lol lol" value = string.split() aList = [] duplicates = [] countedDict = {} for i in value: if i not in aList: aList.append(i) else: duplica
string = "btu got punished by btu lol lol"
value = string.split()
aList = []
duplicates = []
countedDict = {}
for i in value:
if i not in aList:
aList.append(i)
else:
duplicates.append(i)
for i in aList:
if i in duplicates:
duplicates.append(i)
for x in duplicates:
countedDict[x] = len([x])
尝试使用字典理解:
string = "btu got punished by btu lol lol"
print({k: string.count(k) for k in string.split()})
输出:
{'btu': 2, 'got': 1, 'punished': 1, 'by': 1, 'lol': 2}
{'btu': 2, 'got': 1, 'punished': 1, 'by': 1, 'lol': 2}
或者,如果您可以使用集合
模块,请使用:
from collections import Counter
string = "btu got punished by btu lol lol"
print(Counter(string.split()))
您可以尝试以下方法:
string = "btu got punished by btu lol lol"
occur = {}
value = string.split()
for i in value:
c = 0
for j in value:
if i ==j:
c+=1
occur[i]=c
输出:
{'btu': 2, 'got': 1, 'punished': 1, 'by': 1, 'lol': 2}
{'btu': 2, 'got': 1, 'punished': 1, 'by': 1, 'lol': 2}
你的词典理解需要时间复杂度。O(N^2)。你剩下的问题基本上没问题。