python - 需要帮助在 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 个重复元素?谢谢
解决方案
您的错误是因为您的author
变量是列表列表,这是一个示例:
from collections import Counter
Counter([[1], [2]])
输出:
TypeError: unhashable type: 'list'
您不需要将author
元素存储为列表,您必须更改此行:author += [[row[4]]]
使用author += [row[4]]
或author.append(row[4])
推荐阅读
- javascript - 如何使用 node.js javascript 创建 jwt
- java - 如何防止密码重新生成?
- xml - 如何根据 xslt 的元素是否存在来选择值
- excel - Powershell 文本到列
- position - 节点的世界位置始终是原点 - ARKit 锚点
- apache-kafka - 使用 Kafka Streams DSL 合并两个 Kafka 主题的事件时间
- colors - 使用 Fortran 删除 Sublime Text 3 中制表符的颜色
- azure - 生成 EventGrid 并将 AzureFunction 定义为 Endpoint
- ada - 如何确定 Ada 文件是使用静态还是动态精化编译的
- apache-spark - PySpark 数据帧操作导致 OutOfMemoryError