迭代

字典迭代

obj = {"name": "tenro", "age": 27, "sex": "男"}

#遍历字典的键
for key in obj:
  print(key)

#遍历字典的值
for value in obj.values():
  print(value)

#同时遍历字典中的键和值
for key, value in obj.items():
  print(key)
  print(value)
  print(key, ":", value)

列表及元祖迭代

arr = ['tenro', 28, '男']

#迭代出数组里面的元素
for value in arr:
  print(value)

# 迭代出数组里面的索引及对应的元素
for i, value in enumerate(arr):
  print(i, ":", value)


tup = [(1, 1), (2, 2), (3, 3)] #数组里面放入元祖
tuq = [[1, 1], [2, 2], [3,3]]  #二维数组

for(x, y) in tup:
  print(x, y)
for(z, w) in tuq:
  print(z, w)


for x, y in tup:
  print(x, y)
for x, y in tuq:
  print(z, w)

字符串迭代

str = "my name is tenro, i'm 28 years old and a cute boy"
for i in str:
  print(i)

你可能感兴趣的:(迭代)