- 获取文件名后缀
def get_suffix(file_name): pos = file_name.rfind('.') if 0 < pos < len(file_name) - 1: return file_name[pos:] else: return '' print(get_suffix('ddd.txt'))
总结:0 < pos < len(file_name) - 1是一种比较新奇的写法;截取字符串时省略后面的参数表示截取到字符串的最后
- 返回一个数组中的最大和最小两个数
def get_max_2(li): m1, m2 = (li[0], li[1]) if li[0] > li[1] else (li[1], li[0]) for i in range(2, len(li)): if li[i] > m1: m2 = m1 m1 = li[i] elif li[i] > m2: m2 = li[i] return m1, m2 print(get_max_2([1, 2, 3, 4, 1000, 31, 43, 10000]))
总结:python可以给两个变量同时赋值,写法x1, x2 = list
- 计算指定日期是一年中的第几天
#判断年份是否是闰年 def is_leap_year(year): return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 #获取某日期是一年中的第几天 def get_day_index(year, month, date): days_of_month = [ [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ][is_leap_year(year)] total_days = 0 for i in range(month - 1): total_days += days_of_month[i] total_days += date return total_days print(get_day_index(2018, 2, 10))