python - 如何从列表中删除重复键

标签 python python-3.x csv

我的csv文件

student,gender,id

jimmy,male,001
joe,male,002
joe,male,002
hugo,female,003

我的代码

with open('student.csv', 'r') as csv_file, open('new_student.csv', 'w', newline='') as new_file:
    csv_reader = csv.reader(csv_file)
    csv_writer = csv.writer(new_file, delimiter=',', quotechar='"',)

    list_1 = list(csv_reader)

    for line in list_1:

        data = [['jimmy', 'male', '001'], ['joe', 'male', '002'],['joe', 'male', '002'],['hugo', 'female', '003']]

        set(data)

set 方法将命中 TypeError: unhashable type: 'list'。如果我尝试像 data= line(dict.fromkeys(data))

一样的错误

最佳答案

可变类型(例如列表)不能用作集合和字典中的键。将内部列表转换为不可变的元组:

>>> set(map(tuple, data))
{('jimmy', 'male', '001'), ('hugo', 'female', '003'), ('joe', 'male', '002')}

map(tuple, data) 等同于:

  • tuple(d) for d in data 在 Python 3.x 中
  • [tuple(d) for d in data] 在 Python 2.x 中——在这里使用 itertools.imap 会更高效

关于python - 如何从列表中删除重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55490984/

相关文章:

python - 有没有办法优化MYSQL REPLACE功能?

python-3.x - python 计算元组中的出现次数

python - 添加脚本以将 python 结果从 json 导出到 excel 或 csv 文件

python csv - 导出数据和格式颜色、文本格式等

python - 按列写入 csv

python - 无法在 Scrapy 中获取所有 http 请求

如果落在另一个 df 的日期范围之间,python 将值分配给 pandas df

python - 如何使用Biopython获取残留物中的原子

python - python virtualenv中的sudo权限

python - 删除目录 python3 中最旧的文件