Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何向集合中添加和删除元素,需要注意什么 #27

Open
Sogrey opened this issue Feb 15, 2020 · 0 comments
Open

如何向集合中添加和删除元素,需要注意什么 #27

Sogrey opened this issue Feb 15, 2020 · 0 comments

Comments

@Sogrey
Copy link
Owner

Sogrey commented Feb 15, 2020

添加和删除集合中的元素

x = {3,2,1}
x.add(123) ## 添加元素  
print(x)  ## {123, 1, 2, 3}
x.add(1) ## 集合中添加重复元素,结果不会重复元素
print(x)  ## {123, 1, 2, 3}
x.add('abc')  ## 集合中可包含不同数据类型的元素
print(x)  ## {1, 2, 3, 'abc', 123}  不是按顺序存储

x.remove(123)  ## 删除元素
if x.__contains__(444):  ## 删除元素前应先判断是否存在,删除不存在的元素会抛出异常
    x.remove(444)
else:
    print('444在集合中不存在')
@Sogrey Sogrey added this to 列表、元祖、字典 in Python QAs Feb 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Python QAs
列表、元祖、字典
Development

No branches or pull requests

1 participant