15 个提高效率的 Python 编程技巧 (转)

转自:https://www.infoq.cn/article/gGWTBjWt3xHiEQQQMgJa

英文原文: 15 Python tips and tricks, so you don’t have to look them up on Stack Overflow

做个笔记,留文存档。

1. 交换值

x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)

2. 字符串列表合并为一个字符串

sentence_list = ["my", "name", "is", "George"]
sentence_string = " ".join(sentence_list)
print(sentence_string)

3. 将字符串拆分为子字符串列表

sentence_string = "my name is George"
sentence_string.split()
print(sentence_string)

4. 通过数字填充初始化列表

[0]*1000 # List of 1000 zeros 
[8.2]*1000 # List of 1000 8.2's

5. 字典合并

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}

6. 反转字符串

name = "George"
name[::-1]

7. 从函数返回多个值

def get_a_string():
  a = "George"
  b = "is"
  c = "cool"
  return a, b, c
sentence = get_a_string()
(a, b, c) = sentence

8. 列表解析式

a = [1, 2, 3]
b = [num*2 for num in a] # Create a new list by multiplying each element in a by 2

9. 遍历字典

m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} 
for key, value in m.items():
  print('{0}: {1}'.format(key, value))

10. 同时遍历列表的索引和值

m = ['a', 'b', 'c', 'd']
for index, value in enumerate(m):
  print('{0}: {1}'.format(index, value))

11. 初始化空容器

a_list = list()
a_dict = dict()
a_map = map()
a_set = set()

12. 删除字符串两端的无用字符

name = "  George "
name_2 = "George///"
name.strip() # prints "George"
name_2.strip("/") # prints "George"

13. 列表中出现最多的元素

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))

14. 检查对象的内存使用情况

import sys
x = 1
print(sys.getsizeof(x))

15. 将 dict 转换为 XML

from xml.etree.ElementTree import Element
def dict_to_xml(tag, d):
    '''
    Turn a simple dict of key/value pairs into XML
    '''
    elem = Element(tag)
    for key, val in d.items():
        child = Element(key)
        child.text = str(val)
        elem.append(child)
    return elem

DeepOps的python小笔记-整型数字转换为2进制 8进制 16进制

1 将 其它进制 转换为 整型

>>> int('10101', 2) #2进制
21
>>> int('17',8) # 8进制
15
>>> int('ef',16) # 16进制
239
>>> int('14' ,7 ) # 7进制的不支持,不能瞎输
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 7: '7'
>>> int(0b10101) #2进制数字前加0b
21
>>> int(0o17) # 8进制数字前加0o
15
>>> int(0xef) # 16进制数字前加0x
239

2 将整型 转换为 其它进制的

#bin(整型) #二进制
#oct(整型) #八进制
#hex(整型) #十六进制

>>> bin(90)
'0b1011010'
>>> oct(90)
'0o132'
>>> hex(90)
'0x5a'

3 ASCII码的转换

>>>chr(66) 
'B' 
>>>ord('D') 
68 

DeepOps的python小笔记-安装anaconda后,终端前面多一个(base)

ubuntu 和 MacOS 安装了 anaconda 后,打开终端后机器名前面都会有一个 (base),是因为启动终端的时候,会自动启动conda的base环境,如果看着不顺眼可以使用下面的命令进行关闭。可以用 conda env list 查看conda 的环境。

$ conda config --set auto_activate_base false

可以手动激活与关闭这个环境

$ conda activate base 
$ conda deactivate

参考资料:
https://blog.csdn.net/u010666669/article/details/90085125
https://blog.csdn.net/IDzengkun/article/details/89491437