Python迭代(列表、字典、元组)的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cj675816156/article/details/80043217
# Pyhon列表
list_a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Pyhon元组
tuple_a = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
# Python字典
dict_a = {'a': 1, 'b': 2, 'c': 3}

# 可迭代对象的父类
from collections import Iterable
# 判断列表、元组、字典是否是可迭代对象
print(isinstance(list_a, Iterable),
isinstance(tuple_a, Iterable),
isinstance(dict_a, Iterable))
# 迭代列表
for i in list_a:
    print(i)
# 迭代列表,顺带获得索引了
for i, v in enumerate(list_a):
    print(i, v)
# 迭代字典中的值
for value in dict_a.values():
    print(value)
# 迭代字典中的键和值
for k, v in dict_a.items():
    print(k, v)
# 迭代由元组作为元素组成的列表
for x, y in [(1, 1), (2, 4), (3, 9)]:
    print(x, y)

猜你喜欢

转载自blog.csdn.net/cj675816156/article/details/80043217