在Python中设置 [英] Sets in Python

查看:58
本文介绍了在Python中设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我最近尝试在Python中使用set函数并且感到惊讶

找到


a = [ 1,2,3,[1,2]]

不能使用''set'',抛出TyperError(不可避免的异常)。我发现这是因为列表无法进行哈希处理。


因此,这意味着''a''不能在python中设置我认为这很不幸,毕竟''a''确实看起来像数学集。


我的问题是,

1)为什么不能列出哈希值?



2)这是没有关系的,但是我有干净的方式(没有pop和list

comprehension)将一组转换成一个列表?我说整齐,因为我是b / b
猜测使用列表理解可能会变慢而且

可能是其他更快的方法。

感谢您的时间

SM

Hello,
I recently tried using the set function in Python and was surprised to
find that

a=[ 1, 2,3, [1,2] ]

doesn''t work with ''set'', throwing TyperError (unhashable exception). I
found out that this is because lists can''t be hashed.

So,this implies ''a'' cannot be a set in python which i think is quite
unfortunate, after all ''a'' does look like a mathematical set.

My question is,
1) Why can''t lists be hashed?
and
2) This is not related, but is there i neat way (without pop and list
comprehension) to convert a set into a list? I say neat because i''m
guessing using list comprehension might turn out be slow and there
might be other methods which are faster.

Thank you for your time
SM

推荐答案

sapsi写道:
sapsi wrote:

2)这是没有关系的,但是我有一个简洁的方法(没有pop和list

comprehension)将一个集合转换成一个列表吗?我说整洁,因为我是b / b
猜测使用列表理解可能会变得很慢而且

可能是更快的其他方法。
2) This is not related, but is there i neat way (without pop and list
comprehension) to convert a set into a list? I say neat because i''m
guessing using list comprehension might turn out be slow and there
might be other methods which are faster.



a = set([1,2,3,4])

b = list(a)

a = set([1, 2, 3, 4])
b = list(a)


9月18日下午5:39,sapsi< saptarshi.g ... @ gmail.comwrote:
On Sep 18, 5:39 pm, sapsi <saptarshi.g...@gmail.comwrote:

我最近尝试过使用Python中的set函数很惊讶

找到


a = [1,2,3,[1,2]]


不能使用''set'',抛出TyperError(不可避免的异常)。我发现这是因为列表不能被散列。

所以,这意味着''a''不能在python中设置,我认为是相当不幸的是,毕竟''a'看起来像一个数学集合。
I recently tried using the set function in Python and was surprised to
find that

a=[ 1, 2,3, [1,2] ]

doesn''t work with ''set'', throwing TyperError (unhashable exception). I
found out that this is because lists can''t be hashed.
So,this implies ''a'' cannot be a set in python which i think is quite
unfortunate, after all ''a'' does look like a mathematical set.



这写成:


a = set([1,2,3,frozenset([1,2]) )])

This is written as:

a = set([1, 2, 3, frozenset([1, 2])])


这是没有关系的,但是我有一个简洁的方法(没有pop和list

comprehension)将一个集合转换成一个列表?
This is not related, but is there i neat way (without pop and list
comprehension) to convert a set into a list?



list(a)

Raymond

list(a)
Raymond


9月19,10:39 am,sapsi< saptarshi.g ... @ gmail.comwrote:
On Sep 19, 10:39 am, sapsi <saptarshi.g...@gmail.comwrote:

我的问题是,

1 )为什么不能列出哈希?
My question is,
1) Why can''t lists be hashed?



它们是可变的。

They are mutable.


这篇关于在Python中设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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