25実用的で簡潔なPythonコード

今日コンパイルされた25の一般的に使用されるPythonコードスニペットを断固として収集してください。それが十分に役立つと思われる場合は、周囲の友人や同僚と共有することを忘れないでください〜

12つの変数の値を交換します

num_1, num_2 = 666, 999# 一行代码搞定交换两个变量的值num_1, num_2 = num_2, num_1print(num_1, num_2)输出:999 666
Process finished with exit code 0

2オブジェクトが使用するメモリを見つけます

import sys
slogan = "今天你学python了么?"size = sys.getsizeof(slogan)print(size)输出:100
Process finished with exit code 0

3文字列を逆にします

slogan = "今天你学习python了么?"# 一行代码搞定字符串的反转new_slogan = slogan[::-1]print(new_slogan)输出:?么了nohtyp习学你天今Process finished with exit code 0

4弦が回文であるかどうかを確認します

# 定义一个判断字符串是否是回文的函数def is_palindrome(string):    return string == string[::-1]
示例:调用判断函数来进行判断slogan是否是回文字符串slogan = "今天你学python了么?"_ = is_palindrome(slogan)print(_)输出:False
Process finished with exit code 0

5文字列のリストを1つの文字列に結合します

slogan = ["今", "天", "你", "学", "python", "了", "么", "?"]# 一行代码搞定将字符串列表合并为单个字符串real_slogan = "".join(slogan)print(real_slogan)输出:今天你学python了么?
Process finished with exit code 0

62つのリストのいずれかに存在する要素を見つけます

# 定义一个函数用来查找存在于两个列表中任一列表存在的元素def union(list1, list2):    return list(set(list1 + list2))
示例:调用该函数用来查找存在于两个列表中任一列表存在的元素list1, list2 = [5, 2, 0], [5, 2, 1]new_list = union(list1, list2)print(new_list)输出:[0, 1, 2, 5]
Process finished with exit code 0

7文字列をN回印刷します

slogan = "今天你学python了么?"new_slogan = 11*sloganprint(new_slogan)输出:今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?今天你学python了么?
Process finished with exit code 0

8チェーン比較

number = 100print(98<number<102)输出:True
Process finished with exit code 0
print(100==number<102)输出:True
Process finished with exit code 0

9ワードケース

slogan = "python happy"# 一行代码搞定单词大小写转换print(slogan.upper())
# 一行代码搞定单词首字母大写print(slogan.capitalize())
# 一行代码搞定将每个单词的首字母转为大写,其余小写print(slogan.title())输出:PYTHON HAPPYPython happyPython Happy
Process finished with exit code 0

10リスト内の要素の頻度を数えます

from collections import Counter

numbers = [1, 1, 3, 2, 4, 4, 3, 6]# 一行代码搞定求列表中每个元素出现的频率count = Counter(numbers)print(count)输出:Counter({1: 2, 3: 2, 4: 2, 2: 1, 6: 1})
Process finished with exit code 0

11文字列に含まれる要素が同じかどうかを判断します

from collections import Counter

course = "python"new_course = "ypthon"count_1, count_2 = Counter(course), Counter(new_course)if count_1 == count_2:    print("两个字符串所含元素相同!")输出:两个字符串所含元素相同!
Process finished with exit code 0

12数値の文字列を数値のリストに変換します

string = "666888"numbers = list(map(int, string))print(numbers)输出:[6, 6, 6, 8, 8, 8]
Process finished with exit code 0

13 enumerate()関数を使用して、インデックスと値のペアを取得します

string = "python"for index, value in enumerate(string):    print(index, value)输出:0 p1 y2 t3 h4 o5 n
Process finished with exit code 0

14コードの実行には時間がかかる

import time
start_time = time.time()
numbers = [i for i in range(10000)]
end_time = time.time()time_consume = end_time - start_timeprint("代码执行消耗的时间是:{}".format(time_consume))输出示例:代码执行消耗的时间是:0.002994537353515625
Process finished with exit code 0

15セットと辞書のルックアップ効率の比較

import time
number = 999999# 生成数字列表和数字集合numbers = [i for i in range(1000000)]digits = {i for i in range(1000000)}
start_time = time.time()# 列表的查找_ = number in numbersend_time = time.time()
print("列表查找时间为:{}".format(end_time - start_time))
start_time = time.time()# 集合的查找_ = number in digitsend_time = time.time()
print("集合查找时间为:{}".format(end_time - start_time))输出:列表查找时间为:0.060904741287231445集合查找时间为:0.0
Process finished with exit code 0

16辞書のマージ

info_1 = {"apple": 13, "orange": 22}info_2 = {"爆款写作": 48, "跃迁": 49}# 一行代码搞定合并两个字典new_info = {**info_1, **info_2}print(new_info)输出:{'apple': 13, 'orange': 22, '爆款写作': 48, '跃迁': 49}Process finished with exit code 0

17ランダムサンプリング

import random
books = ["爆款写作", "这个世界,偏爱会写作的人", "写作七堂课", "越书写越明白"]# 随机取出2本书阅读reading_book = random.sample(books, 2)print(reading_book)输出:['这个世界,偏爱会写作的人', '越书写越明白']
Process finished with exit code 0

18リスト内の要素の一意性を判断する

# 定义一个函数判断列表中元素的唯一性def is_unique(list):    if len(list) == len(set(list)):        return True    else:        return False
    # 调用该函数判断一个列表是否是唯一性的numbers = [1, 2, 3, 3, 4, 5]_ = is_unique(numbers)print(_)输出:FalseProcess finished with exit code 0

19階乗再帰関数の実装を計算する

def fac(n):    if n > 1:        return n*fac(n-1)    else:        return 1
number = int(input("n="))print("result = {}".format(fac(number)) )输出:n=5result = 120
Process finished with exit code 0

20現在のディレクトリ内のすべてのファイルとディレクトリ名を一覧表示します

import os

files = [file for file in os.listdir(".")]print(files)输出:['.idea', '2048.py', 'access.log', 'beautiful_girls', 'beautiful_girls_photos', 'boy.py', 'cache.json', 'catoffice.py', 'cookie.json', 'data.csv', 'data.txt', 'diary', 'files', 'filtered_words.txt', 'geckodriver.log', 'get_movies_info2.py', 'girl.py', 'girl1.py', 'ha.conf', 'homework.py', 'homework3.py', 'index.html', 'info.ini', 'notepad.py', 'rent.csv', 'stock.txt', 'student.txt', 'student.xlsx', 'student_register_info.json', 'test.png', 'test_picture.txt', 'zhihu.html', '__pycache__', '九尾1997_200行代码实现2048小游戏.py', '九尾1997_python实现图片转字符画.py', '九尾1997_实现一个简单的计算器.py', '九尾1997_爬取优美图美女写真.py', '九尾1997_爬取北京58租房信息.py', '九尾1997_路飞学城注册页面', '校园管理系统.py', '爬虫模拟登录.py', '记事本.m4a']
Process finished with exit code 0

21元の辞書のキーと値のペアを逆にして、新しい辞書を作成します

dict_1 = {1: "python", 2: "java"}new_dict = {value:key for key, value in dict_1.items()}print(new_dict)输出:{'python': 1, 'java': 2}
Process finished with exit code 0

22九九の九九を印刷する

for i in range(1, 10):    for j in range(1, i+1):        print("{} * {} = {}".format(i, j, i*j), end="")    print()输出:1 * 1 = 1 2 * 1 = 2 2 * 2 = 4 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 
Process finished with exit code 0

231か月あたりの日数を計算します

import calendar
month_days = calendar.monthrange(2025,8)print(month_days)输出:(4, 31)
Process finished with exit code 0

24検証コードをランダムに生成し、ランダムモジュールを呼び出します

import random, string
str_1 = "0123456789"# str_2 是包含所有字母的字符串str_2 = string.ascii_lettersstr_3 = str_1 + str_2# 多个字符中选取特定数量的字符verify_code = random.sample(str_3, 6)# 使用join方法拼接转换为字符串verify_code = "".join(verify_code)print(verify_code)输出:Mk0L6Y
Process finished with exit code 0

25うるう年の判断

year  = input("请输入一个年份:")year = int(year)# 一行代码判断年份是否是闰年if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:    print("{}是闰年!".format(year))else:    print("{}不是闰年!".format(year))输出示例:请输入一个年份:20002000是闰年!
Process finished with exit code 0

996はインターネット上で常に一般的な話題ですが、それ以外は仕事そのものについてのみ話します。仕事が比較的非効率的であるために、遅刻したり残業したりすることがあると思ったことはありませんか。

したがって、より有用で、一般的に使用され、簡潔なコードセグメントを蓄積することが本当に必要です。

繰り返しになりますが、これらのコードスニペットが役に立った場合は、ブックマークして、友達や同僚と共有することを忘れないでください〜

おすすめ

転載: blog.csdn.net/BYGFJ/article/details/123786546
おすすめ