Python基础知识为何set()可以工作,但是{}失败? [英] Python basics why set() works but {} fails?
本文介绍了Python基础知识为何set()可以工作,但是{}失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
s = ["this", "that", "this"]
为什么 set 起作用,但是
{s}
失败
Why does set(s)
work but {s}
fails with
TypeError: unhashable type: 'list'
推荐答案
这是因为它们含义不同. set(s)
迭代 s
以创建一个集,而字面语法 {s}
只是尝试创建一个包含单个元素的集<代码> s .
It's because they mean different things. set(s)
iterates s
to create a set, whereas the literal syntax {s}
just attempts to create a set containing the single element s
.
>>> set("abc")
{'a', 'b', 'c'}
>>> {"abc"}
{'abc'}
尝试使用 {* s}
代替等效的 set
.
Try {*s}
instead for the equivalent of set(s)
.
这篇关于Python基础知识为何set()可以工作,但是{}失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文