首页 > 解决方案 > 需要帮助在 python 的列表中查找重复元素

问题描述

import csv
import re
from collections import Counter
with open('articles.txt',encoding="ANSI") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
author = []
#publication = []
#for row in csv_reader:
    #publication += [[row[3]]]
for row in csv_reader:
    author += [[row[4]]]
count = 0
NPR_list=[]
for number in range(1,len(new_file)):
    if 'NPR'== str(new_file[number][3]):
       NPR_list.append(author[number])
       count+= 1
for remove in range(1,273):
    NPR_list.remove([''])
list(NPR_list)     
print(NPR_list)
Counter(NPR_list).mostcommon(5)

它将返回一个错误,TypeError: unhashable type: 'list' 如何更改代码以使其返回前 5 个重复元素?谢谢

标签: pythonlistduplicates

解决方案


您的错误是因为您的author变量是列表列表,这是一个示例:

from collections import Counter

Counter([[1], [2]])

输出:

TypeError: unhashable type: 'list'

您不需要将author元素存储为列表,您必须更改此行:author += [[row[4]]]使用author += [row[4]]author.append(row[4])


推荐阅读