标题 创建时间 发布时间 最后一次修改 备注
Python 常见问题速查 2020.08.04 2020.12.21 2020.12.21 /

获取日期参数输入,或者默认日期

import sys
import time

if len(sys.argv)==2:
    today = sys.argv[1]
else:
    today = time.strftime("%Y-%m-%d", time.localtime())

对list元素进行判断

# source: https://thispointer.com/python-count-elements-in-a-list-that-satisfy-certain-conditions/

listOfElems = [11, 22, 33, 45, 66, 77, 88, 99, 101]
# count numbers in the list which are greater than 5
count = sum(map(lambda x : x>5, listOfElems)) # lambda 函数可替换

print('Count of numbers in a list which are greater than 5: ', count)

str类型的array转array

def str2array(current_str):
    '''
    返回数值数组
    '''
    current_array = current_str.replace(']','').replace('[','').replace('"','').split(",")
    current_array = np.array(current_array)
    return [int(numeric_string) for numeric_string in current_array]
  
current_str = '["1","2"]'
str2array(current_str)
>>> [1, 2]

python 取整

# refer: http://kuanghy.github.io/2016/09/07/python-trunc

import math
# 向上取整
math.ceil(2.25)
>>> 3

# 向下取整
int(3.4)
>>> 3
math.floor(2.75)
>>> 2

# 特别注意⚠️ round 取整
round(3.5)
>>> 4
round(2.5)
>>> 2

# 为何会这样:是为了保证整体分布和均值不变。如果每遇*.5进一,则整体均值会上移,带来误差。

关于作者