Python推导与迭代(学习笔记)


在这里插入图片描述

迭代

列表内部过程模拟

scores = [85, 76, 42, 56, 98, 77, 98]

I = iter(scores)  #I为迭代器对象
I.__next__()
I.__next__()
.
.
.
.
I.__next__()       #直到输出98 再迭代会报错  StopIteration异常
#next(I)


#捕获异常正常输出
while True:
    try:
        s = next(I)
        except StopIteration:
                break
        print(s)


students = ['tom', 'Jerry', 'Nike']
I = iter(students)
s = next(I)
s.upper()        #输出TOM
s = I.__next__()
s.upper()        #输出 JERRY
s = i.__next__()
s                     #输出Nike
next(I)            #报错    StopIteration异常

字典

emp = {'name': 'Tom', 'salary': 8000, 'job': 'dev'}
type(emp.keys())        #查看字典 键的类型为dict_keys(可迭代)
for key in emp.keys():
    print(key)            #输出 name salary job

type(emp.values())        #查看字典 值的类型为dict_values(可迭代)
for value in emp.value.values():
    print(value)            #输出 Tom 8000 dev

for k,v in emp.items():
    print({} > {}.format(k, v))
#打印结果
'''
name -> Tom
salary -> 8000
job -> dev
'''

文件

'''
data.txt内容
1
2
3
'''

f = open('data.txt', 'r', encoding='utf-8')
f.read()        #输出data文件内容 1
f.read()        #输出为空

f.seek(0)        #把指针移到文件开头
f.read()        #输出data文件内容  1

f.seek(0)
f.readline()    #输出一行  1
f.readline()    #再输出一行  2

f.seek(0)

lines = f.readlines()    #将所有行读到一个列表里
lines                    #输出['1\n', '2\n', '3']

for line in lines:
    print(line)
#输出为      
'''
1

2

3
'''
f = open('data.txt', 'r', 'encoding='utf-8')
next(f)
输出'1\n'

f.__next__()
输出'2\n'
f.__next__()
输出'3\n'

f.__next__()        #报错   StopIteration异常
f = open('data.txt' , 'r', encoding='utf8')
iter(f) is f		#运行结果为True  表示f为可迭代对象

#可以使用for .. in ..
for line in open('data.txt', 'r', 'encoding='utf8'):
    print(line)      

推导

scores = (85, 76, 42, 56, 98, 77, 98)
results = []
for x in scores:
    result.append(x)
results        #输出[85, 76, 42, 56, 98, 77, 98]
#推导式
results = [x for x in scores]
results        #输出[85, 76, 42, 56, 98, 77, 98]

#map()内置函数

results3 = map(lambda x: x + 2, scores)    #每个数字加2
results3        #map对象

list(results3)    #转换为list对象

#推导式
results = [x + 2 for x in scores]

students = ['Tom', 'Jerry', 'Mike']
[n.upper() for n in students]



#filter()内置函数


print(list(filter(lambda x: x>=60, scores)))        #输出分数大于60的
#推导式
[x for x in scores if x >= 60]                           #使出分数大于60的

students = ['Tom', 'Jerry', 'Mike']

[n for n in students if 'e' in n]            #输出含有e的


[x + 2 for x in scores if x <= 60]                                #将小于60的加两分

#{}返回集合
{s for s in scorces}        #去重  因为集合是一个无序的不重复元素序列


#()推导返回是生成器而不是元组
t = (s for s in scores)        
type(t)                    #t为生成器类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值