[英]Python - TypeError: Unhashable type list error
I'm trying to create a comprehension that takes each value n in a list and returns the values from 1-n. 我正在尝试创建一个理解,以获取列表中的每个值n并从1-n返回值。 IE for
[1,2,4]
the return should be [[1],[1,2],[1,2,3,4]]
. IE对于
[1,2,4]
的返回应该是[[1],[1,2],[1,2,3,4]]
。 My code is getting this unhashable type list
error. 我的代码收到此
unhashable type list
错误。
{range(x) for x in {1,2,4}}
Braces - {}
creates a Set of the element you pass to it. 大括号-
{}
创建传递给它的元素的Set。 To create a list, you need to use brackets - []
要创建列表,您需要使用方括号-
[]
[range(x) for x in [1,2,4]]
And to get the required output, you need to change your range()
a little bit. 为了获得所需的输出,您需要稍微更改一下
range()
。 range(2)
will give you [0, 1]
instead of [1, 2]
. range(2)
会给您[0, 1]
而不是[1, 2]
。
You can use: 您可以使用:
>>> [range(1, x+1) for x in [1, 2, 4]]
[[1], [1, 2], [1, 2, 3, 4]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.