Python常用语句

mac2022-07-05  31

遍历文件

方式一

from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

方式二

from os import walk f = [] for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break

参考How to list all files of a directory?

以文件的保存的编码打开文件

有时候在打开文件的时候,不知道文件的编码。这个时候就需要先探测到文件的编码,然后再以探测到的文件编码打开。但是在Python中并没有相关的包可以用来获取文件的编码,可以借助于第三方的库chardet

安装chardet

pip install chardet

打开文件

with open(filpath,'rb') as file: rawdata = file.read() result = chardet.detect(rawdata) charenc = result['encoding'] content = rawdata.decode(charenc,'ignore')

更新pip

更新pip3

pip3 install --upgrade pip

更新pip2

pip2 install --upgrade pip

得到所有的字符

很多时候需要使用Python得到所有字符,包括特殊字符。

import string string.printable

最后的结果为

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;?@[\\]^_`{|}~ \t\n\r\x0b\x0c

连续数字

有时候需要生成等长的数字序列,如001,002一直到100 使用常规的range只能生成普通的1,2,3这样的字符串。 可以使用zfill()函数来完成

num = [str(i) for i in range(100)] new_nums = [] for i in num: i = i.zfill(3) new_nums.append(i) print(new_nums)

其中的zfill(3)就是表示需要生成三位数的数字 最后的结果就是:

将dict以json格式保存

import json with open('result.json', 'w') as fp: json.dump(sample, fp)

Flatten (an irregular) list of lists

不知道如何翻译成为中文,但是看代码示例就应该知道了。

简单的方式(规则的list)

import itertools list2d = [[1, 2, 3], [4, 5, 6], [7], [8, 9,],[12,]] merged = list(itertools.chain.from_iterable(list2d)) print(merged) #output:[1, 2, 3, 4, 5, 6, 7, 8, 9, 12]

可以看到list2d是一个二级list,如果出现3级list,那么上述的方法就会失败。

import itertools list2d = [[1, 2, 3,[11,12,13]],[4,5,6,[14,15,16]]] merged = list(itertools.chain.from_iterable(list2d)) print(merged) #output:[1, 2, 3, [11, 12, 13], 4, 5, 6, [14, 15, 16]]

说明使用itertools.chain.from_iterable只能解压两层

递归的方式

面对不同形式的list,最好的方式是使用递归来解决。

def flatten(x): import collections if isinstance(x, collections.Iterable): return [a for i in x for a in flatten(i)] else: return [x] def get_flattern_List(): list2d = [[1, 2, 3], [4, 5, 6], [7], [8, 9, [10, 11,[12,13]]]] result = flatten(list2d) print(result) #output:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

使用递归的方式,可以解决不规则的list的问题。

转载于:https://www.cnblogs.com/babers/p/6746162.html

相关资源:第3章 Python常用语句.pptx
最新回复(0)