温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python如何创建集合

发布时间:2022-03-31 10:32:08 来源:亿速云 阅读:389 作者:小新 栏目:开发技术

这篇文章主要介绍了python如何创建集合,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

集合的创建方法

通过 set 函数创建集合,也可以使用有值的大括号来创建。 如 {1, 2} ,但不能使用空的大括号来创建。(空的大括号是一个空的字典)

示例如下:

test_set_01 = set()				# ---> 一个空的集合
test_set_02 = set([1, 2, 3])	# ---> 传入列表或元组
test_set_03 = {1, 2, 3}			# ---> 传入元素
test_set_04 = {}  				# ---> 这样的方式是错误的,这是一个空的字典

print(type(test_set_04))

# 执行结果如下:
# ---> <class 'dict'>
test_list_01 = ['name', 'age', 'birthday']
test_set_01 = set(test_list_01)
print(test_set_01)

# 执行结果如下:
# >>> {'name', 'age', 'birthday'}		可以看到,传入的并不是列表,而是列表的元素


test_list_02 = ['name', 'age', 'birthday', 'age']
test_set_02 = set(test_list_02)
print(test_set_02)

# 执行结果如下:
# >>> {'name', 'age', 'birthday'}		可以看到,列表里重复的元素,做了去重的处理


test_list_03 = (1, 2, 3, 1, 5)
test_set_03 = set(test_list_03)
print(test_set_03)

# 执行结果如下:
# >>> {1, 2, 3, 5}						可以看到,元组里重复的元素,做了去重的处理


test_set_04 = {['name', 'age', 'birthday']}
print(test_set_04)

# 执行结果如下:
# >>> TypeError: unhashable type: 'list'	集合内不可传入列表,否则会报错


test_set_05 = {{'name', 'age', 'birthday'}}
print(test_set_05)

# 执行结果如下:
# >>> TypeError: unhashable type: 'set' 	集合内同样也不可传入字典


test_set_06 = {'name', 1, 3.14, (666, 888)}
print(test_set_06)

# 执行结果如下:
# >>> {'name', 3.14, 1, (666, 888)}			集合内可以传入不同的数据类型(列表不可以直接传入)

感谢你能够认真阅读完这篇文章,希望小编分享的“python如何创建集合”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI