for .. in ..方式遍历可迭代对象
而非下标
## 判断是否可迭代
from collections import Iterable
print(isinstance(123,Iterable))
print(isinstance('abc',Iterable))
print(isinstance([],Iterable))
print(isinstance({},Iterable))
## 打印str下标和值
for k,v in enumerate('abc'):
print(k,v)
print('------------')
for k,v in enumerate({'a':1,'b':2}):
print(k,v)
- 求arr的最大值
- 求arr的最大的2个值
- 求arr的max和min
# 求arr的最大值
arr = [11,2,3]
max_num = 0
for i in arr:
if i > max_num:
max_num = i
print(max_num)
# 找出arr最大的两个值
## 思路,找2个游标,看i落在哪里了.
max_num = 0
sec_num = 0
arr = [1, 2, 2, 3]
for i in arr:
if i < sec_num:
sec_num = i
elif i > sec_num and i < max_num:
sec_num = i
elif i > max_num:
sec_num = max_num
max_num = i
print(sec_num, max_num)
# 找出最大最小值
# 迭代查找一个list中最小和最大值,并返回一个tuple
arr = [1, 2, 1, 3, 4, 5]
def get_min_max(arr):
max_num = arr[0]
min_num = arr[0]
if len(arr) == 0:
return ""
for i in arr:
if i < min_num:
min_num = i
if i > max_num:
max_num = i
print(min_num, max_num)
return (min_num, max_num)
get_min_max(arr)