python字典和列表的遍历,文件读写的常用操作

字典,列表遍历,文件

Posted by 粘世强 on March 31, 2018

遍历

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-value
for c in dic:
    print(c,':',dic[c])

结果:

1 : 21
2 : 64
3 : 98

3. 输出字典内容的另一种方法

#遍历字典的内容
dict1 = {'abc':1,"cde":2,"d":4,"c":567,"d":"key1"}
for k,v in dict1.items():
    print(k,":",v)
abc : 1
cde : 2
d : key1
c : 567

4. 遍历输出列表的序号和内容

#enumerate函数使用
sequence = [12, 34, 34, 23, 45, 76, 89]
for i, j in enumerate(sequence):
    print(i, j)
0 12
1 34
2 34
3 23
4 45
5 76
6 89

5. 遍历多个列表,使用zip函数

#同时遍历两个或更多的序列,可以使用 zip() 组合,这个很有意思
questions = ['name', 'quest', 'favorite color']
answers1 = ['lancelot', '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 lancelot.
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)
9
7
5
3
1

文件的读写常用操作

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', ' 认真学习'] ​