双休或者放假期间,我就适合不工作然后学点自己想学的、感兴趣的。[捂脸]
map()用于对容器中元素进行映射,省掉了遍历这一步,很方便。
def f(x):
return x * 2
data = [1, 2]
a = f(data)
print(a) # [1, 2, 1, 2]
b = map(f, data)
print(b) #
c = list(map(f, data))
print(c) # [2, 4]
# 如果要实现map的功能:
d = []
for i in data:
y = f(i)
d.append(y)
print(d) # [2, 4]
filter()用于对容器中的元素进行过滤处理,同样不用去遍历每个元素。
def f(x):
return x > 3
data = [2, 5, 6, 9, 3, 2, 1]
a = list(filter(f, data))
print(a) # [5, 6, 9]
所谓异常机制,就是指程序出现问题时依然可以正确的执行剩余的程序,而不会因为异常而终止程序执行。
我一般用try–except语句,但处理方式有很多,比如:
with open('test.txt', 'r') as f:
for line in f.readlines():
print(line)
我知道的不再赘述。
如果有中文,打开文件时要加上 encoding = ‘utf-8’
with open('school/bookcontent/result2/a.txt', 'w', encoding='utf-8') as f:
s = ['xiaoxi', 'xiaoming']
f.write(s) # TypeError: write() argument must be str, not list
with open('school/bookcontent/result2/a.txt', 'w', encoding='utf-8') as f:
s = ['xiaoxi', 'xiaoming']
f.writelines(s) # xiaoxixiaoming
with open('school/bookcontent/result2/a.txt', 'w', encoding='utf-8') as f:
s = ['xiaoxi\n', 'xiaoming\n']
f.writelines(s)
>>> xiaoxi
xiaoming
with open('school/bookcontent/result2/a.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
>>> xiaoxi
xiaoming
with open('school/bookcontent/result2/a.txt', 'r', encoding='utf-8') as f:
content = f.readline()
print(content)
>>> xiaoxi
with open('school/bookcontent/result2/a.txt', 'r', encoding='utf-8') as f:
content = f.readlines()
print(content)
>>>['xiaoxi\n', 'xiaoming\n']
现在知道为啥用f.readlines()读取文件内容后,要用strip(’\n’)去掉换行符了。
我一般用pandas中的pd.read_csv(),但还可以用csv包。
os模块可以帮助我们直接对操作系统进行操作,调用文件、命令等。我总结一些我自己常用的吧。
常用库列表:
Pypingyin: 汉字拼音转换工具
人类知识真真真浩如烟海,你绝对可以找到自己感兴趣的并且愿意主动去学习的东西!加油。最后万物归于一物,学思维比学知识重要。