【问题标题】:Python TypeError: unhashable type: 'list''Python TypeError:不可散列的类型:'list''
【发布时间】:2015-07-15 18:09:49
【问题描述】:

一直在尝试在 python 中获取两个 CSV 文件之间的区别。想通过一系列教程,但多次遇到相同的错误。

import csv

f1 = open ("ted.csv")
oldFile1 = csv.reader(f1, delimiter=',')
oldList1 = list(oldFile1)

f2 = open ("ted2.csv")
newFile2 = csv.reader(f2, delimiter=',')
newList2 = list(newFile2)

f1.close()
f2.close()

output1 = set(row for row in newList2 if row not in oldList1)
output2 = set(row for row in oldList1 if row not in newList2)



print (output2.difference(output1))

回溯可以在下面看到

Traceback (most recent call last):
File "C:/tarts/testmrcsv.py", line 14, in <module>
output1 = set(row for row in newList2 if row not in oldList1)
TypeError: unhashable type: 'list'

我的目标是创建第三个 csv 文件。谢谢

【问题讨论】:

标签: python parsing csv python-3.x


【解决方案1】:

list 数据类型没有任何difference 函数,您可能希望创建output1output2 作为设置,示例-

output1 = set(row for row in newList2 if row not in oldList1)
output2 = set(row for row in oldList1 if row not in newList2)

如果 row 的类型是 list ,那么您还应该在输入 set 之前将其转换为 tuple 。示例 -

output1 = set(tuple(row) for row in newList2 if row not in oldList1)
output2 = set(tuple(row) for row in oldList1 if row not in newList2)

【讨论】:

  • 我仍然收到格式 Traceback 的错误(最近一次调用最后一次):文件“C:/tarts/testmrcsv.py”,第 14 行,在 output1 = set(row for row如果行不在 oldList1 中,则在 newList2 中) TypeError: unhashable type: 'list'
【解决方案2】:

列表没有差异方法,但集合有:

>>> print(set(output2).difference(set(output1)))

【讨论】:

  • Im getting Traceback(最近一次调用最后一次):文件“C:/tarts/testmrcsv.py”,第 14 行,在 output1 = set(row for row in newList2 if row not in oldList1) TypeError: unhashable type: 'list'
猜你喜欢
  • 2013-10-22
  • 2013-01-23
  • 2019-01-29
  • 2012-01-21
  • 2017-06-21
  • 2018-10-05
  • 2020-03-28
  • 2021-12-17
  • 1970-01-01
相关资源
最近更新 更多