首页 > 编程知识 正文

python遍历列表间隔,python遍历字典的键

时间:2023-05-04 10:07:39 阅读:270029 作者:773

遍历 1. 遍历字典(只能遍历key值) dic = {"1":21,"2":64,"3":98}#遍历字典只是遍历key值for c in dic: print(c, end = ",")

结果:

1,2,3, 2. 遍历输出完整的字典内容 dic = {"1":21,"2":64,"3":98}#遍历输出完整的key-valuefor c in dic: print(c,':',dic[c])

结果:

1 : 212 : 643 : 98 3. 输出字典内容的另一种方法 #遍历字典的内容dict1 = {'abc':1,"cde":2,"d":4,"c":567,"d":"key1"}for k,v in dict1.items(): print(k,":",v) abc : 1cde : 2d : key1c : 567 4. 遍历输出列表的序号和内容 #enumerate函数使用sequence = [12, 34, 34, 23, 45, 76, 89]for i, j in enumerate(sequence): print(i, j) 0 121 342 343 234 455 766 89 5. 遍历多个列表,使用zip函数 #同时遍历两个或更多的序列,可以使用 zip() 组合,这个很有意思questions = ['name', 'quest', 'favorite color']answers1 = ['专一的曲奇', 'the holy grail', 'blue']answers2 = ["xiaoming","xiaobai","xiaolan"]for q, a,h in zip(questions, answers1,answers2): print('What is your {0}? It is {2}.'.format(q, a,h)) What is your name? It is xiaoming.What is your quest? It is xiaobai.What is your favorite color? It is xiaolan. for q, a,h in zip(questions, answers1,answers2): print('What is your {0}? It is {1}.'.format(q, a,h))#和上一个cell的区别在于引用的序号 What is your name? It is 专一的曲奇.What is your quest? It is the holy grail.What is your favorite color? It is blue. 6. 反向遍历 #反向遍历for i in reversed(range(1, 10, 2)): print(i) 97531 文件的读写常用操作 f = open("aa.txt","w")f.write("正在练习python。n 认真学习")#f.write()写入内容f.close() 区分f.read(),f.readline(),f.readlines() f = open("aa.txt")content = f.read()#f.read()将文件的全部内容读取并返回,返回的内容和文件一致print(content)f.close()

结果:

正在练习python。 认真学习 f = open("aa.txt","r")#f.readline对文件进行逐行读取content = f.readline()content1 = f.readline()print(content)print(content1)f.close() 正在练习python。 认真学习

f = open("aa.txt")#f.readlines()返回文件内容的所有行,每一行作为列表的一个元素content = f.readlines()print(content)f.close() ['正在练习python。n', ' 认真学习']

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。