新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python程序:迭代集合項(xiàng)
創(chuàng)新互聯(lián)Python教程:

網(wǎng)站的建設(shè)創(chuàng)新互聯(lián)公司專注網(wǎng)站定制,經(jīng)驗(yàn)豐富,不做模板,主營網(wǎng)站定制開發(fā).小程序定制開發(fā),H5頁面制作!給你煥然一新的設(shè)計(jì)體驗(yàn)!已為成都廣告制作等企業(yè)提供專業(yè)服務(wù)。
編寫一個(gè) Python 程序來迭代集合項(xiàng)。Python for 循環(huán)是迭代集合項(xiàng)最常見的循環(huán)。在這個(gè)例子中,我們使用 for 循環(huán)來迭代數(shù)字和字符串集。
# Itearte Over Sets
set1 = {10, 20, 30, 40, 50, 60}
print("The Total Items in this Set = ")
for val in set1:
print(val, end = ' ')
set2 = set("Tutorial Gateway")
print("The Total Items in this Set = ")
for char in set2:
print(char, end = ' ')
迭代集合項(xiàng)的 Python 程序
在這里,我們將集合轉(zhuǎn)換為列表,并使用 for 循環(huán)范圍根據(jù)索引迭代和打印集合項(xiàng)。
# Itearte Over Sets
set1 = {11, 33, 55, 77, 99, 111}
list1 = list(set1)
print("The Total Items in this Set = ")
for i in range(len(list1)):
print(list1[i], end = ' ')
set2 = set("TutorialGateway")
list2 = list(set2)
print("\n\nThe Total Items in this Set = ")
for i in range(len(list2)):
print(list2[i], end = ' ')
迭代用于循環(huán)輸出的集合項(xiàng)
The Total Items in this Set =
33 99 55 11 77 111
The Total Items in this Set =
l r G w u i y o t a e T
這個(gè) Python 程序使用枚舉來迭代集合項(xiàng)。一般來說,我們不需要身份證。所以可以在 enumerate(setName)中使用 for _,值。
# Itearte Over Sets
set1 = {11, 33, 55, 77, 99, 111}
print("The Total Items in this Set = ")
for i, value in enumerate(set1):
print(i, value)
set2 = set("Python")
print("\nThe Total Items in this Set = ")
for i, value in enumerate(set2):
print(i, value)
print("\nThe Total Items in this Set = ")
for _, value in enumerate(set1):
print(value, end = ' ')
print("\nThe Total Items in this Set = ")
for _, value in enumerate(set2):
print(value, end = ' ')
迭代設(shè)定值枚舉輸出
The Total Items in this Set =
0 33
1 99
2 55
3 11
4 77
5 111
The Total Items in this Set =
0 y
1 o
2 n
3 t
4 P
5 h
The Total Items in this Set =
33 99 55 11 77 111
The Total Items in this Set =
y o n t P h
這是使用列表和列表理解迭代集合的另一個(gè)例子。
# Itearte Over Sets
set1 = {5, 10, 20, 25, 30, 35, 40}
print("The Total Items in this Set = ")
x = [print(val, end = ' ') for val in set1]
set2 = set("Python")
print("The Total Items in this Set = ")
x = list(val for val in set2)
print(x)
print(*x)
使用列表理解輸出迭代集合項(xiàng)
The Total Items in this Set =
35 20 5 40 25 10 30 The Total Items in this Set =
['h', 'P', 'y', 'o', 't', 'n']
h P y o t n 新聞標(biāo)題:Python程序:迭代集合項(xiàng)
當(dāng)前地址:http://m.5511xx.com/article/dphgdcg.html


咨詢
建站咨詢
