下面是Python对常见数据类型的遍历解析的攻略:
一、列表(List)的遍历
1.1 for循环遍历
lst = [1, 2, 'a', 'b', True]
for i in lst:
print(i)
1.2 for循环遍历+enumerate函数
lst = [1, 2, 'a', 'b', True]
for idx, val in enumerate(lst):
print(idx, val)
1.3 while循环遍历
lst = [1, 2, 'a', 'b', True]
idx = 0
while idx < len(lst):
print(lst[idx])
idx += 1
二、元组(Tuple)的遍历
2.1 for循环遍历
tup = (1, 2, 'a', 'b', True)
for i in tup:
print(i)
2.2 for循环遍历+enumerate函数
tup = (1, 2, 'a', 'b', True)
for idx, val in enumerate(tup):
print(idx, val)
2.3 while循环遍历
tup = (1, 2, 'a', 'b', True)
idx = 0
while idx < len(tup):
print(tup[idx])
idx += 1
三、字典(Dictionary)的遍历
3.1 遍历key
dic = {'name':'Tom', 'age':18, 'gender':'male'}
for key in dic:
print(key)
3.2 遍历value
dic = {'name':'Tom', 'age':18, 'gender':'male'}
for value in dic.values():
print(value)
3.3 遍历key,value
dic = {'name':'Tom', 'age':18, 'gender':'male'}
for key, value in dic.items():
print(key, value)
四、集合(Set)的遍历
4.1 for循环遍历
s = {'a', 'b', 'c', 'd'}
for item in s:
print(item)
4.2 while循环遍历
s = {'a', 'b', 'c', 'd'}
it = iter(s)
while True:
try:
item = next(it)
print(item)
except StopIteration:
break
以上是对Python常见数据类型的遍历解析的攻略,其中以列表和字典为例进行了示范。在实际操作中,需要根据数据的实际情况来选择最适合的遍历方式。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python对常见数据类型的遍历解析 - Python技术站