? ? ?set是一組數,無序,內容不能重復,通過調用set()方法創建,那么如何對set集合進行遍歷呢?
1.簡單的set:
s1 = set(['111', '222', '333'])
對于s1,是一組數,有幾種方法可以遍歷:
function1:直接用in的方式遍歷set集合。
function2:用iter()迭代器來遍歷集合
看到前兩種方法可能有人就有疑問了,為啥和上面寫入s1時候的順序不一樣,別急,往下看。
function3:這種方法只能輸出index,并不能輸出value,因為set不支持set['cols']的讀取方式
function4:可以把index和value同時輸出,看到這里大家應該可以明白,為什么function1和function2輸出是333和222反過來了,因為333的index才是1,而222的index是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.復雜set
s2 = set([('小明', 149), ('小蘭', 120), ('小紅', 140)])
可以看到,這個set有點類似字典,有key和value的感覺,那么這種set如何遍歷呢?其實和上面的方法是一樣的,我們來看下效果
在下面的結果中,可以看到,輸出的順序,其實和我們寫入的是不一樣的,這也是set的特點
注意:set的元素是tuple,因此 在function2和function4時,for 循環的變量被依次賦值為tuple。
function1是對每一組元素讀取,因此是數據本身的類型
#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:
以上是對set兩種形式的遍歷,可能還有更加好的方法,歡迎大家隨時交流
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
