Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在列表中查找事件_Python_Python 3.x_List_Dictionary_Duplicates - Fatal编程技术网

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)。你剩下的问题基本上没问题。