python之小技巧

[TOC]

python检查语法

在终端写python脚本的时候,经常在写完脚本运行的时候,才发现错误。如果某些代码没有运行到,则其中的错误不会被检查出来。这是因为python是一门动态解释型语言。这与用gcc编译C等静态语言时可以发现全局的语法问题有所不同。
为了避免潜在的语法问题。我们在写完python脚本文件之后,最好给python脚本做个静态语法检查,以此来避免低级错误。

检查工具有pyflakes, pylint, pep8, flake8等。这里用pyflakes做一下简单的检查。简单的用法如下:

1
2
pip3 install pyflakes
pyflakes test.py

python字符串中包含大括号时怎么使用string的.format方法?

1
2
3
'hello {name}'.format(name='world')的时候大括号是特殊转义字符,如果需要原始的大括号,用{{代替{, 用}}代替}, 如下:
>>> 'hello {{worlds in braces!}}, {name}'.format(name='zhangsan')
'hello {worlds in braces!}, zhangsan'

python将一组数分成每3个一组的实例

如下所示

1
2
3
4
a = [1,2,3,4,5,6,7,8,9,10,11]
step = 3
b = [a[i:i+step] for i in range(0,len(a),step)]
print(b)

结果:

1
2
3
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
>>> b[1]
[4, 5, 6]

Python中字符串、列表、元组、字典之间的相互转换

https://www.jb51.net/article/174331.htm

字符串

字符串转换为列表

  1. 使用list()方法
1
2
3
4
5
6
7
8
9
10
11
12
str_1 = "1235"
str_2 = 'zhangsan'
str_3 = '''lisi'''
tuple_1 = list(str_1)
tuple_2 = list(str_2)
tuple_3 = list(str_3)
print(type(tuple_1))
print(type(tuple_2))
print(type(tuple_3))
print(tuple_1)
print(tuple_2)
print(tuple_3)

结果:

img

  1. 使用Python中字符串的内置方法split()

    Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
    语法:str.split(str=””, num=string.count(str)).
    ①str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
    ②num – 分割次数。默认为 -1, 即分隔所有。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    str_1 = "12 35 213"
    str_2 = 'zhang san shi a '
    str_3 = 'zhang san shi a '
    str_4 = '''li si wang wu'''
    list_1 = str_1.split(" ")
    list_2 = str_2.split(" ",1)
    list_3 = str_3.split(" ")
    list_4 = str_4.split(" ",2)
    print(type(list_1))
    print(type(list_2))
    print(type(list_3))
    print(type(list_4))
    print(list_1)
    print(list_2)
    print(list_3)
    print(list_4)

    结果:

    img

字符串 转换为 元组

使用tuple()方法

1
2
3
4
5
6
7
8
9
10
11
12
str_1 = "1235"
str_2 = 'zhangsan'
str_3 = '''lisi'''
list_1 = tuple(str_1)
list_2 = tuple(str_2)
list_3 = tuple(str_3)
print(type(list_1))
print(type(list_2))
print(type(list_3))
print(list_1)
print(list_2)
print(list_3)

结果:

img

字符串 转换为 字典

利用eval()方法,可以将字典格式的字符串转换为字典

eval() 函数用来执行一个字符串表达式,并返回表达式的值。
语法:eval(expression[, globals[, locals]])
①expression – 表达式。
②globals – 变量作用域,全局命名空间,如果被提供���则必须是一个字典对象。③locals – 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

1
2
3
4
str_1 = "{'name':'zhangsan','age':14,'gender':'girl'}"
dict_1 = eval(str_1)
print(type(dict_1))
print(dict_1)

结果:

img

利用json.loads()方法,可以将字典格式的字符串转换为字典

json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
语法:json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

1
2
3
4
5
6
import json

str_1 = '{"name":"xiaoming","age":18}'
dict_1 = json.loads(str_1)
print(type(dict_1))
print(dict_1)

结果:

img

列表

列表转字符串

利用‘’.join()将列表中的内容拼接程一个字符串

Python join() 方法用于将序列中的元素(必须是str) 以指定的字符(‘’中指定的) 连接生成一个新的字符串。

1
2
3
4
list_1 = ['a', 'b', 'c']
str_1 = ''.join(list_1)
print(type(str_1))
print(str_1)

结果:

img

列表转字典

利用for in rang将两个列表转换为字典

1
2
3
4
5
6
7
list_1 = ['a', 'b', 'c']
list_2 = [1, 2, 3]
dict_1 = {}
for i in range(len(list_1)):
dict_1[list_1[i]] = list_2[i]
print(type(dict_1))
print(dict_1)

结果:

img

利用python内置方法dict()和zip()将两个列表转换为字典

dict() 函数用于创建一个字典。
语法:class dict(kwarg)
class dict(mapping, *kwarg)
class dict(iterable, *
kwarg)①
kwargs – 关键字
②mapping – 元素的容器。
③iterable – 可迭代对象。

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
语法:zip([iterable, …])
iterabl – 一个或多个迭代器;

1
2
3
4
5
list_1 = ['name', 'age']
list_2 = ['zhangsan',18]
dict_1 = dict(zip(list_1, list_2))
print(type(dict_1))
print(dict_1)

结果:

img

元组(tuple)

元组转换为字符串

  • 使用方法__str__
  • 返回一个对象的描述信息
1
2
3
4
tuple_1 = (1, 2, 3)
str_1 = tuple_1.__str__()
print(type(str_1))
print(str_1)

结果:

img

元组转换为列表

使用方法list()

list() 方法用于将元组转换为列表。
语法:list( tup )
tup – 要转换为列表的元组。

1
2
3
4
tuple_1 = (1, 2, 3)
list_1 = list(tuple_1)
print(type(list_1))
print(list_1)

结果:

img

字典(dict)

字典转换为字符串

使用 json.dumps()方法

json.dumps 用于将 Python 对象编码成 JSON 字符串。
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None,encoding=“utf-8”, default=None, sort_keys=False, **kw)

字典转换为元组

  • 使用方法 tuple()
  • 字典在转换为元组之后,只会保存关键字
1
2
3
4
5
dict_1 = {"name":"zhangsan",
"age":18}
tuple_1 = tuple(dict_1)
print(type(tuple_1))
print(tuple_1)

结果:

img

字典转换为列表

  • 使用方法 list()
  • 字典在转换为列表之后,只会保存关键字
1
2
3
4
5
dict_1 = {"name":"zhangsan",
"age":18}
list_1 = list(dict_1)
print(type(list_1))
print(list_1)

结果:

img

--------------------本文结束,感谢您的阅读--------------------

本文标题:python之小技巧

文章作者:弓昭

发布时间:2020年03月15日 - 15:02

最后更新:2021年04月21日 - 20:39

原始链接:https://gongzhao1.gitee.io/python之小技巧/

联系邮箱:gongzhao1@foxmail.com