Python 集合(Sets)2

访问项

您无法通过引用索引或键来访问集合中的项。但是,您可以使用for循环遍历集合项,或者使用in关键字检查集合中是否存在指定的值。

示例,遍历集合并打印值:

1thisset = {"apple", "banana", "cherry"} 2 3for x in thisset: 4 print(x)

示例,检查集合中是否存在 "banana":

1thisset = {"apple", "banana", "cherry"} 2 3print("banana" in thisset)

Python - 添加集合项

一旦创建了集合,您就不能更改其项,但可以添加新项。要向集合添加一个项,请使用add()方法。

示例,使用add()方法向集合添加一个项:

1thisset = {"apple", "banana", "cherry"} 2 3thisset.add("orange") 4 5print(thisset)

要将另一个集合中的项添加到当前集合中,请使用update()方法。

示例,将tropical中的元素添加到thisset中:

1thisset = {"apple", "banana", "cherry"} 2tropical = {"pineapple", "mango", "papaya"} 3 4thisset.update(tropical) 5 6print(thisset)

添加任何可迭代对象

update()方法中的对象不必是集合,可以是任何可迭代对象(元组、列表、字典等)。

示例,将列表的元素添加到集合中:

1thisset = {"apple", "banana", "cherry"} 2mylist = ["kiwi", "orange"] 3 4thisset.update(mylist) 5 6print(thisset)

Python - 删除集合项

要删除集合中的项,可以使用remove()discard()方法。

示例,使用remove()方法删除 "banana":

1thisset = {"apple", "banana", "cherry"} 2 3thisset.remove("banana") 4 5print(thisset)

注意:如果要删除的项不存在,remove()将引发错误。

示例,使用discard()方法删除 "banana":

1thisset = {"apple", "banana", "cherry"} 2 3thisset.discard("banana") 4 5print(thisset)

注意:如果要删除的项不存在,discard()不会引发错误。

您还可以使用pop()方法来删除一个项,但此方法将删除一个随机项,因此不能确定删除哪个项。pop()方法的返回值是已删除的项。

示例,使用pop()方法删除一个随机项:

1thisset = {"apple", "banana", "cherry"} 2 3x = thisset.pop() 4 5print(x) 6 7print(thisset)

注意:由于集合是无序的,因此在使用pop()方法时无法确定删除哪个项。

示例,clear()方法将清空集合:

1thisset = {"apple", "banana", "cherry"} 2 3thisset.clear() 4 5print(thisset)

示例,del关键字将完全删除集合:

1thisset = {"apple", "banana", "cherry"} 2 3del thisset 4 5print(thisset)

Python - 遍历集合

您可以使用for循环遍历集合项:

示例,遍历集合并打印值:

1thisset = {"apple", "banana", "cherry"} 2 3for x in thisset: 4 print(x)

希望这些信息对您有所帮助!如果有任何问题或需要更多解释,请随时提问。

最后

为了方便其他设备和平台的小伙伴观看往期文章,链接奉上:

公众号搜索Let us Coding知乎开源中国CSDN思否掘金InfoQ简书博客园慕课51CTOhelloworld腾讯开发者社区阿里开发者社区

看完如果觉得有帮助,欢迎点赞、收藏关注

点赞
收藏

评论区

加载中...

相关推荐

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

Python - 字典2

Python访问字典项您可以通过在方括号内引用其键名来访问字典的项:示例,获取"model"键的值:Pythonthisdict"brand":"Ford","model":"Mustang","year":1964xthisdict,,,,,,,,,看完

Python 集合(Sets)1

集合集合用于在单个变量中存储多个项。集合是Python中的4种内置数据类型之一,用于存储数据集合,其他3种是列表(List)、元组(Tuple)和字典(Dictionary),它们都具有不同的特性和用途。集合是一种无序、不可更改()、无索引的集合。创建一个

mysql中like用法

like的通配符有两种%(百分号):代表零个、一个或者多个字符。\(下划线):代表一个数字或者字符。1\.name以"李"开头wherenamelike'李%'2\.name中包含"云",“云”可以在任何位置wherenamelike'%云%'3\.第二个和第三个字符是0的值wheresalarylike'\00%'4\

Java练习(三)——返回集合中的最大的和最小的元素

题目:在一个列表中存储以下元素:apple,grape,banana,pear,现要求将集合进行排序,返回集合中的最大的和最小的元素,并将排序后的结果打印在控制台上,要求的打印输出方法分别为默认toString输出、迭代器输出、for循环遍历输出和增强for循环输出。packagetest;importjava.util.;publicclassP