Python:TypeError:无法散列的类型:'sl​​ice' [英] Python: TypeError: unhashable type: 'slice'

查看:90
本文介绍了Python:TypeError:无法散列的类型:'sl​​ice'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python阅读CSV,这是代码.

I am reading CSV using python, here is the code.

train_csv = open('train.csv')
test_csv = open('test.csv')
train_data_reader = csv.DictReader(train_csv)
test_data_reader = csv.DictReader(test_csv)

row=[]
for row in train_data_reader:
    X.append([int(item) for item in row[4:]]) 
    char = row[1]
    Y.append(charIntConversion(char))
    train_id.append(row[0])
    prediction.append(row[1])
for row in test_data_reader:
    test_id.append(row[0])
    test_X.append([int(item) for item in row[4:]]

当我尝试运行代码时,它表明TypeError:不可散列的类型:'sl​​ice'for

when I tried to run the code, it shows that TypeError: unhashable type: 'slice' for

X.append([int(item) for item in row[4:]])
test_X.append([int(item) for item in row[4:]] 

X和test_X应该包含从CSV的第4列到最后一列的值.

X and test_X should contain the value from column 4 to last column of the CSV.

我可以知道我的代码有什么问题,如何解决此问题?

May I know what's wrong with my code and how can I fix this issue?

推荐答案

我可以看到您已经解决了您的问题,但是我想在这里给以后的读者留下答案.谁可能会被这个(我刚刚)抓住.

I can see you have resolved your issue, but I thought I'd leave an answer here for any future readers. Who might get caught by this (I just was).

问题在于该对象是字典,您正试图将其传递给切片,该切片不可散列,因此不能用作字典键.

The issue is that the object is a dictionary and you are trying to pass it a slice, which is not hashable and hence cant be used as a dict key.

简单的例子

>>> d = {0: 5, 1: 6, 2: 7, 3: 8, 4: 9}
>>> d[:5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'slice'

您想要做的是从集合中获取n个项目.因此,实现此目的的方法是首先将dict转换为列表(可切片).为此,请根据您的使用情况使用dict.itemsdict.keysdict.values.

What you are trying to do is take n items from the collection. So the way to achieve this is to first convert the dict to a list (which is sliceable). To do this use dict.items, dict.keys or dict.values depending on your use case.

没有命令dict(尽管有最新的python 3.6开发),所以您从dict.items(或朋友)那里得到的东西可能对您没有帮助.因此,您可以在制作切片之前对其进行排序.

A dict (recent python 3.6 development notwithstanding) is not ordered and so what you will get back from dict.items (or friends) may not be in an order useful to you. So you can sort it before making the slice.

>>> sorted(d.items())[:5]
[(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]

上面的代码有点难看,但是可以.

The above code is slightly ugly, but works.

您可以通过使用itertools中的islice来避免编制索引

You could avoid the indexing by using islice from itertools

>>> from itertools import islice
>>> list(islice(sorted(d.items()), 5))
[(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]

如果默认排序顺序不是您想要的,您将提供一个排序键.这种方法效率低下,因为它会在切片前对整个集合进行排序,尽管不确定如何解决.

You'd provide a key to sort if the default sorting order was not what you wanted. This way is inefficient as it sorts the entire collection before slicing, not sure of a way around that though.

到达此页面并被上述错误困扰的任何人都不会意识到他们正在尝试在字典上进行切片.在字典上执行切片实际上并没有多大意义,大多数有经验的开发人员会意识到,如果这样做,您将要求不可预测的结果.

Anyone arriving at this page and being puzzled by the above error, will not have realised they are attempting a slice on a dictionary. Performing a slice on a dictionary, doesn't really make a lot of sense and most experienced developers would realise that if you do that you are asking for an unpredictable result.

如果您确实想从字典中获取前n个元素,请说说csv文件中的一行,其中的列按规定的顺序排列.最好将所需的键格式化为元组,然后从dict中获取这些元素.

If you genuinely do want to take the first n elements from a dictionary, say a row from a csv file where the columns are in some prescribed order. It would be much better to format the required keys into a tuple and just take those elements from the dict.

例如

仅获取字典中的前两列

people = [{'name': 'paul', 'job': 'programmer', 'age': 'old'}, 
          {'name': 'chris', 'job': 'student', 'age': 'young'}]

>>> for p in people:
...     res = [p[key] for key in ('name', 'job')]
...     print(res)
['paul', 'programmer']
['chris', 'student']

hth

这篇关于Python:TypeError:无法散列的类型:'sl​​ice'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆