額,,離藍橋杯開賽還有十個小時,最近因為考研復習節奏的問題,把藍橋杯的優先級后置了,突然才想起來還有一個藍橋杯呢。。
到目前為止python基本語法熟練了,再補充一些常用函數供明天考前再背背,算法來不及看了,eh,嘿嘿...祝友友們都能拿省一!
?
一、字符串
1.ASCII碼函數
print(ord('L')-ord('A')+65)
ord()
函數可以將字符轉換為對應的ASCII碼,chr()
函數可以將ASCII碼轉換為對應的字符
?
2.字母大小寫函數
upper() 方法
upper() 方法將字符串中的所有小寫字母轉換為大寫字母。
lower() 方法
lower() 方法將字符串中的所有大寫字母轉換為小寫字母。
capitalize() 方法
capitalize() 方法將字符串的第一個字母轉換為大寫,其余字母轉換為小寫。
title() 方法
title() 方法將每個單詞的首字母轉換為大寫,其余字母轉換為小寫。
?
3.分割函數
str.split(sep=None,maxsplit=-1)
表示:使用sep子字符串分割字符串str。maxsplit是最大分割次數
str.rsplit(sep=None,maxsplit=-1)
表示:從右到左分割字符串
4.字符串列表轉int列表
list = [ int(i) for i in str]
?
?
?
?
?
二、時間函數
datetime.datetime
函數說明
datetime.datetime
是 Python 中 datetime
模塊的一個類,用于處理日期和時間。通過該類可以創建一個包含日期和時間的對象。
-
datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0)
創建一個日期時間對象,參數包括年、月、日、時、分、秒和微秒。例如:datetime.datetime(1970, 1, 1, 0, 0, 0) ?# 表示紀元時間起點
常用日期和時間函數總結
1. 日期時間的創建與解析
-
datetime.datetime.now()
獲取當前的日期和時間。now = datetime.datetime.now()
-
datetime.datetime.strptime(date_string, format)
將字符串按指定格式解析為datetime
對象。dt = datetime.datetime.strptime("2023-10-01 12:30:45", "%Y-%m-%d %H:%M:%S")
-
datetime.datetime.strftime(format)
將datetime
對象格式化為字符串。formatted = dt.strftime("%Y-%m-%d %H:%M:%S")
2. 日期時間的運算
-
datetime.timedelta
表示兩個日期或時間之間的差值,支持加減運算。delta = datetime.timedelta(days=1, hours=2, minutes=30) new_time = datetime.datetime.now() + delta
-
datetime.datetime.timestamp()
將datetime
對象轉換為時間戳(自紀元時間以來的秒數)。timestamp = datetime.datetime.now().timestamp()
-
datetime.datetime.fromtimestamp(timestamp)
將時間戳轉換為datetime
對象。dt = datetime.datetime.fromtimestamp(1696138245)
3. 日期時間的屬性
-
year
,month
,day
,hour
,minute
,second
,microsecond
獲取datetime
對象的各個部分。dt = datetime.datetime.now() print(dt.year, dt.month, dt.day)
-
weekday()
和isoweekday()
獲取星期幾,weekday()
返回 0(周一)到 6(周日),isoweekday()
返回 1(周一)到 7(周日)。print(dt.weekday(), dt.isoweekday())
4. 其他常用功能
-
datetime.date.today()
獲取當前日期(不包含時間)。today = datetime.date.today()
-
datetime.time(hour=0, minute=0, second=0, microsecond=0)
創建一個時間對象。t = datetime.time(12, 30, 45)
-
datetime.datetime.combine(date, time)
將日期和時間組合成一個datetime
對象。combined = datetime.datetime.combine(datetime.date.today(), datetime.time(12, 30))
?
用一道真題融會貫通
問題描述
小藍發現了一個神奇的鬧鐘,從紀元時間(19701970?年?11?月?11?日?00:00:0000:00:00)開始,每經過?xx?分鐘,這個鬧鐘便會觸發一次鬧鈴 (紀元時間也會響鈴)。這引起了小藍的興趣,他想要好好研究下這個鬧鐘。
對于給出的任意一個格式為?уууу-MM-ddHH:mm:ssуууу-MM-ddHH:mm:ss?的時間,小藍想要知道在這個時間點之前 (包含這個時間點) 的最近的一次鬧鈴時間是哪個時間?
注意,你不必考慮時區問題。
輸入格式
輸入的第一行包含一個整數?TT,表示每次輸入包含?TT?組數據。
接下來依次描述?TT?組數據。
每組數據一行,包含一個時間(格式為?уууу-MM-ddHH:mm:ssуууу-MM-ddHH:mm:ss)和一個整數?xx,其中?xx?表示鬧鈴時間間隔(單位為分鐘)。
輸出格式
輸出?TT?行,每行包含一個時間(格式為?уууу-MM-ddHH:mm:ssуууу-MM-ddHH:mm:ss),依次表示每組數據的答案。
樣例輸入
2
2016-09-07 18:24:33 10
2037-01-05 01:40:43 30
?
樣例輸出
2016-09-07 18:20:00
2037-01-05 01:30:00
?
評測用例規模與約定
對于所有評測用例,1≤T≤10,1≤x≤10001≤T≤10,1≤x≤1000,保證所有的時間格式都是合法的。
?
思路
當作練習日期的函數很好
思路就是:用輸入的時間和1970這個日期的差值對鬧鈴時間間隔取余,由此得到輸入的時間和上一次鬧鈴響的時刻的時間差值(分鐘),減去就行
關鍵點在于掌握時間函數的用法。
?
代碼
import datetimen = int(input())
for _ in range(n):time = input().rsplit(" ", 1)delt = int(time[1])oratime = datetime.datetime.strptime('1970-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')nowtime = datetime.datetime.strptime(time[0], '%Y-%m-%d %H:%M:%S')x = (nowtime - oratime) % datetime.timedelta(minutes=delt)finaltime = nowtime - xprint(finaltime)
三、 常用排序函數
sorted()函數
-
功能: 返回一個新的排序后的列表。
-
參數:
-
iterable
: 可迭代對象(如列表、元組等)。 -
key
(可選): 一個函數,用于從每個元素中提取比較鍵。 -
reverse
(可選): 布爾值,True
表示降序排序,默認為False
(升序)。
-
# 示例
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 輸出: [1, 2, 5, 5, 6, 9]# 使用 key 參數
words = ["banana", "apple", "cherry"]
sorted_words = sorted(words, key=len)
print(sorted_words) # 輸出: ['apple', 'banana', 'cherry']# 降序排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # 輸出: [9, 6, 5, 5, 2, 1]
list.sort() 方法
-
功能: 對列表進行原地排序。
-
參數:
-
key
(可選): 一個函數,用于從每個元素中提取比較鍵。 -
reverse
(可選): 布爾值,True
表示降序排序,默認為False
(升序)。
-
# 示例
numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(numbers) ?# 輸出: [1, 2, 5, 5, 6, 9]
?
# 使用 key 參數
words = ["banana", "apple", "cherry"]
words.sort(key=len)
print(words) ?# 輸出: ['apple', 'banana', 'cherry']
?
# 降序排序
numbers.sort(reverse=True)
print(numbers) ?# 輸出: [9, 6, 5, 5, 2, 1]
四、?藍橋杯其它常用函數
(1) 輸入輸出
-
input()
: 從標準輸入讀取一行數據。 -
print()
: 將數據輸出到標準輸出。
(2) 字符串操作
-
str.split(separator)
: 將字符串按指定分隔符分割成列表。 -
str.join(iterable)
: 將可迭代對象中的元素連接成一個字符串。 -
str.strip()
: 去除字符串兩端的空白字符。 -
str.splitlines()
: 按行分割字符串。
# 示例
text = "a b c\nd e f"
lines = text.splitlines()
print(lines) ?# 輸出: ['a b c', 'd e f']
?
words = "a,b,c".split(",")
print(words) ?# 輸出: ['a', 'b', 'c']
?
joined = " ".join(words)
print(joined) ?# 輸出: 'a b c'
(3) 列表操作
-
list.append(element)
: 在列表末尾添加一個元素。 -
list.extend(iterable)
: 將可迭代對象中的所有元素添加到列表末尾。 -
list.insert(index, element)
: 在指定位置插入一個元素。 -
list.remove(element)
: 刪除列表中第一個匹配的元素。 -
list.pop([index])
: 刪除并返回指定位置的元素,默認為最后一個元素。 -
list.index(element)
: 返回元素在列表中的第一個匹配索引。 -
list.count(element)
: 返回元素在列表中出現的次數。 -
list.sort()
: 對列表進行原地排序。 -
list.reverse()
: 反轉列表中的元素順序。
# 示例
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) ?# 輸出: [1, 2, 3, 4]
?
numbers.extend([5, 6])
print(numbers) ?# 輸出: [1, 2, 3, 4, 5, 6]
?
numbers.insert(0, 0)
print(numbers) ?# 輸出: [0, 1, 2, 3, 4, 5, 6]
?
numbers.remove(3)
print(numbers) ?# 輸出: [0, 1, 2, 4, 5, 6]
?
popped = numbers.pop()
print(popped) ?# 輸出: 6
print(numbers) ?# 輸出: [0, 1, 2, 4, 5]
?
index = numbers.index(2)
print(index) ?# 輸出: 2
?
count = numbers.count(1)
print(count) ?# 輸出: 1
?
numbers.sort(reverse=True)
print(numbers) ?# 輸出: [4, 2, 1, 0]
?
numbers.reverse()
print(numbers) ?# 輸出: [0, 1, 2, 4]
(4) 數組操作
-
array.array(typecode, initializer)
: 創建一個數組對象。 -
array.append(x)
: 在數組末尾添加一個元素。 -
array.extend(iterable)
: 將可迭代對象中的所有元素添加到數組末尾。 -
array.insert(i, x)
: 在指定位置插入一個元素。 -
array.remove(x)
: 刪除數組中第一個匹配的元素。 -
array.pop([i])
: 刪除并返回指定位置的元素,默認為最后一個元素。 -
array.index(x)
: 返回元素在數組中的第一個匹配索引。 -
array.count(x)
: 返回元素在數組中出現的次數。
import array
?
# 示例
arr = array.array('i', [1, 2, 3])
arr.append(4)
print(arr) ?# 輸出: array('i', [1, 2, 3, 4])
?
arr.extend([5, 6])
print(arr) ?# 輸出: array('i', [1, 2, 3, 4, 5, 6])
?
arr.insert(0, 0)
print(arr) ?# 輸出: array('i', [0, 1, 2, 3, 4, 5, 6])
?
arr.remove(3)
print(arr) ?# 輸出: array('i', [0, 1, 2, 4, 5, 6])
?
popped = arr.pop()
print(popped) ?# 輸出: 6
print(arr) ?# 輸出: array('i', [0, 1, 2, 4, 5])
?
index = arr.index(2)
print(index) ?# 輸出: 2
?
count = arr.count(1)
print(count) ?# 輸出: 1
(5) 集合操作
-
set()
: 創建一個集合對象。 -
set.add(element)
: 添加一個元素到集合。 -
set.update(iterable)
: 將可迭代對象中的所有元素添加到集合。 -
set.remove(element)
: 刪除集合中指定的元素。 -
set.discard(element)
: 刪除集合中指定的元素,如果不存在則不報錯。 -
set.pop()
: 刪除并返回集合中的一個元素。 -
set.clear()
: 清空集合。 -
set.union(iterable)
: 返回兩個集合的并集。 -
set.intersection(iterable)
: 返回兩個集合的交集。 -
set.difference(iterable)
: 返回兩個集合的差集。 -
set.symmetric_difference(iterable)
: 返回兩個集合的對稱差集。
# 示例
set1 = {1, 2, 3}
set2 = {3, 4, 5}
?
set1.add(4)
print(set1) ?# 輸出: {1, 2, 3, 4}
?
set1.update([5, 6])
print(set1) ?# 輸出: {1, 2, 3, 4, 5, 6}
?
set1.remove(3)
print(set1) ?# 輸出: {1, 2, 4, 5, 6}
?
set1.discard(7) ?# 不會報錯
print(set1) ?# 輸出: {1, 2, 4, 5, 6}
?
popped = set1.pop()
print(popped) ?# 輸出: 1 或其他元素
print(set1) ?# 輸出: {2, 4, 5, 6}
?
set1.clear()
print(set1) ?# 輸出: set()
?
union_set = set1.union(set2)
print(union_set) ?# 輸出: {3, 4, 5}
?
intersection_set = set1.intersection(set2)
print(intersection_set) ?# 輸出: set()
?
difference_set = set1.difference(set2)
print(difference_set) ?# 輸出: set()
?
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) ?# 輸出: {3, 4, 5}
(6) 字典操作
-
dict()
: 創建一個字典對象。 -
dict[key] = value
: 添加或更新鍵值對。 -
dict.get(key, default=None)
: 獲取指定鍵的值,如果不存在則返回默認值。 -
dict.pop(key, default=None)
: 刪除并返回指定鍵的值,如果不存在則返回默認值。 -
dict.keys()
: 返回字典中所有鍵的視圖。 -
dict.values()
: 返回字典中所有值的視圖。 -
dict.items()
: 返回字典中所有鍵值對的視圖。 -
dict.update(iterable)
: 將可迭代對象中的鍵值對更新到字典。 -
dict.clear()
: 清空字典。
# 示例
my_dict = {'a': 1, 'b': 2}
my_dict['c'] = 3
print(my_dict) ?# 輸出: {'a': 1, 'b': 2, 'c': 3}
?
value = my_dict.get('b')
print(value) ?# 輸出: 2
?
popped_value = my_dict.pop('a')
print(popped_value) ?# 輸出: 1
print(my_dict) ?# 輸出: {'b': 2, 'c': 3}
?
keys = my_dict.keys()
print(keys) ?# 輸出: dict_keys(['b', 'c'])
?
values = my_dict.values()
print(values) ?# 輸出: dict_values([2, 3])
?
items = my_dict.items()
print(items) ?# 輸出: dict_items([('b', 2), ('c', 3)])
?
my_dict.update({'d': 4})
print(my_dict) ?# 輸出: {'b': 2, 'c': 3, 'd': 4}
?
my_dict.clear()
print(my_dict) ?# 輸出: {}
(7) 數學運算
-
math
模塊:-
math.ceil(x)
: 向上取整。 -
math.floor(x)
: 向下取整。 -
math.sqrt(x)
: 計算平方根。 -
math.pow(x, y)
: 計算 x 的 y 次方。 -
math.log(x, base)
: 計算以 base 為底的對數。 -
math.sin(x)
,math.cos(x)
,math.tan(x)
: 三角函數。 -
math.factorial(x)
: 計算階乘。 -
math.gcd(a, b)
: 計算最大公約數。
-
import math
?
# 示例
x = 3.7
print(math.ceil(x)) ?# 輸出: 4
print(math.floor(x)) ?# 輸出: 3
?
y = 16
print(math.sqrt(y)) ?# 輸出: 4.0
?
print(math.pow(2, 3)) ?# 輸出: 8.0
?
print(math.log(10, 10)) ?# 輸出: 1.0
?
print(math.sin(math.pi / 2)) ?# 輸出: 1.0
?
print(math.factorial(5)) ?# 輸出: 120
?
print(math.gcd(12, 18)) ?# 輸出: 6
?