首頁>技術>

1. 字串的翻轉

利用切片

利用reduce函式實現

2. 判斷字串是不是迴文串
str1 = "123455"def fun(string):    print("%s" % string == string[::-1] and "YES" or "NO")if __name__ == '__main__':    fun(str1)
3. 單詞大小寫
str1 = "i love you!"print(str1.title())# 單詞首字母大寫print(str1.upper())# 所有字母大寫print(str1.lower())# 所有字母小寫print(str1.capitalize())# 字串首字母大寫
4. 字串的拆分

1.可以使用split()函式,括號內可新增拆分字元,預設空格,返回的是列表

2.去除字串兩邊的空格,返回的是字串

5. 字串的合併

返回的是字串型別

str1 = ["123", "123", "123"]print(''.join(str1))
6. 將元素進行重複
str1 = "python"list1 = [1, 2, 3]# 乘法表述print(str1 * 2)print(list1 * 2)# 輸出# pythonpython# [1, 2, 3, 1, 2, 3]#加法表述str1 = "python"list1 = [1, 2, 3]str1_1 = ""list1_1 = []for i in range(2):    str1_1 += str1    list1_1.append(list1)print(str1_1)print(list1_1)# 輸出同上
7. 列表的拓展
# 修改每個列表的值list1 = [2, 2, 2, 2]print([x * 2 for x in list1])# 展開列表list2 = [[1, 2, 3], [4, 5, 6], [1]]print([i for k in list2 for i in k])# 輸出 [1, 2, 3, 4, 5, 6, 1]
8. 兩個數交換
x = 1y = 2x, y = y, x
9. 統計列表中元素出現的頻率

呼叫collections中的Counter類

from collections import Counterlist1 = ['1', '1', '2', '3', '1', '4']count = Counter(list1)print(count)# 輸出 Counter({'1': 3, '2': 1, '3': 1, '4': 1})print(count['1'])# 輸出 3print(count.most_common(1))# 出現最多次數的 # [('1', 3)]
10. 將數字字串轉化為數字列表
str1 = "123456"# 方法一list_1 = list(map(int, str1))#方法二list_2 = [int(i) for i in str1]
11. 使用enumerat()函式獲取索引數值對
str1 = "123456"list1 = [1, 2, 3, 4, 5]for i, j in enumerate(str1):    print(i, j)'''輸出0 11 22 33 44 55 6'''str1 = "123456"list1 = [1, 2, 3, 4, 5]for i, j in enumerate(list1):    print(i, j)# 輸出同上
12. 計算程式碼執行消耗的時間
import timestart = time.time()for i in range(1999999):    continueend = time.time()print(end - start)# 輸出 0.08042168617248535
13. 檢查物件的記憶體佔用情況

sys.getsizeof()函式

import sysstr1 = "123456"print(sys.getsizeof(str1))# 輸出 55
14. 字典的合併
dirt1 = {'a':2, 'b': 3}dirt2 = {'c':3, 'd': 5}# 方法一combined_dict = {**dirt1, **dirt2}print(combined_dict)# 輸出 {'a': 2, 'b': 3, 'c': 3, 'd': 5}# 方法二dirt1 = {'a':2, 'b': 3}dirt2 = {'c':3, 'd': 5}dirt1.update(dirt2)print(dirt1)# 輸出同上
15. 檢查列表內元素是不是都是唯一的
list1 = [1, 2, 3, 4, 5, 6]print('%s' % len(list1) == len(set(list1)) and "NO" or "YES")

17
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 「轉發」看小姐姐用動圖展示 10 大 Git 命令