Python中set集合的遍历方法详解:function1到function4全解析

集合是一组数字,无序,无法重复内容。它是通过调用set()方法创建的。那么如何穿越设定集合?

Python中set集合的遍历方法详解:function1到function4全解析

1。简单集:

s1 = set(['111', '222', '333'])

对于S1,这是一组数字,有几种遍历的方法:

函数1:直接遍历该方法中的集合集合。

函数2:使用iter()迭代器遍历集合

有些人在看到前两种方法时可能会有疑问,为什么上面写下S1的顺序?不用担心,读下来。

函数3:此方法只能输出索引,而不是值,因为集合不支持set ['cols']的读取方法

函数4:您可以同时输出索引和值。当您看到这一点时,应该了解function1和function2输出为何为333和222逆转,因为333的索引为1,而索引的索引为222为2。输出如下以下标准输出,从小到大。

#function1
for value in s1:
    print (x)
--------结果---------
111
333
222
#function2
for value in iter(s1):
    print (value)
--------结果---------
111
333
222
#function3
for index in range(len(s1)):
    print (index)
--------结果---------
0
1
2
#function4
for index, value in enumerate(s1):
    print ('index:',index,'value:',value)
--------结果---------
index: 0 value: 111
index: 1 value: 333
index: 2 value: 222

2。复杂集

s2 = set([('小明', 149), ('小兰', 120), ('小红', 140)])

如您所见,此集合与词典有点相似,带有钥匙和价值感觉,那么您如何穿越此组合呢?实际上,它与上述方法相同。让我们看一下效果。

在以下结果中,我们可以看到输出顺序实际上与我们编写的内容不同,这也是集合的特征

注意:集合的元素是元组,因此,当function2和function4时,将for循环的变量分配给了元组。

函数1是为每个元素读取的,因此是数据本身的类型

#function1
for row in s2:
    print ('index:',row[0],'value:',row[1])
    print('type:',type(row[0]),'type:',type(row[1]))
------------结果-------------
index: 小兰 value: 120
type:  type: 
index: 小明 value: 149
type:  type: 
index: 小红 value: 140
type:  type: 
#function2
for value in iter(s2):
    print (value)
    print('type:',type(value))
------------结果-------------
('小兰', 120)
type: 
('小明', 149)
type: 
('小红', 140)
type: 
#function3
for index in range(len(s2)):
    print (index)
------------结果-------------
0
1
2
#function4
for index, value in enumerate(s2):
    print ('index:',index,'value:',value)
    print('type:',type(index),'type:',type(value))
------------结果-------------
index: 0 value: ('小兰', 120)
type:  type: 
index: 1 value: ('小明', 149)
type:  type: 
index: 2 value: ('小红', 140)
type:  type: 

以上是两种形式的遍历,并且可能有更好的方法。欢迎每个人随时进行交流。

你可能想看:
« 上一篇
下一篇 »

相关推荐

python爬虫教程PDF,Python爬虫书PDF

2026年09月02日

31阅读

外国教程python,python编程教学视频

2026年09月02日

25阅读

python简明教程沈洁元,python详细基础教程

2026年09月02日

21阅读

python库包教程,python 包

2026年09月02日

27阅读

python教程大全集,python教程600集

2026年09月02日

26阅读

python入门教程完整版,python零基础入门全套教程视频

2026年09月02日

22阅读