1. ホーム
  2. Python

知っておきたいPythonの一行コード50選

2022-02-14 09:59:11
<パス

知っておきたい50の一行Pythonコード


Pythonを使うと、特定のタスクを簡単に達成できることにいつも驚かされます。もっと面倒な作業も、Pythonを使えば1行のコードでできてしまうのです。ここでは、私が集めたPythonの1行コードの50の例を紹介します。

1.レターシフター:文字の数と頻度が同じかどうかを当てる

from collections import Counter  
 
s1 = 'bow'  
s2 = 'elbow'  

print('anagram') if Counter(s1) == Counter(s2) else print('not an anagram')

or we can also do this using the sorted() method like this.

print('anagram') if sorted(s1) == sorted(s2) else print('not an anagram')

decimal = int('1010', 2)  
print(decimal) #10

"Hi my name is Allwin".lower() 
# 'hi my name is allwin'  

"Hi my name is Allwin".casefold()  
# 'hi my name is allwin'

"hi my name is Allwin".upper()  
# 'HI MY NAME IS ALLWIN'

"convert string to bytes using encode method".encode()  
# b'convert string to bytes using encode method'

import shutil; shutil.copyfile('source.txt', 'dest.txt')

qsort = lambda l : l if len(l)<=1 else qsort([x for x in l[1:] if x < l[0]]) + [l[0]] + qsort([x for x in l[1:] if x >= l[0]])

sum(range(0, n+1))

This is not efficient and we can do the same using the formula below.

sum_n = n*(n+1)//2

a,b = b,a

fib = lambda x: x if x<=1 else fib(x-1) + fib(x-2) # The correct Fibonacci series function
fib(8) # The result should be 21

[item for sublist in main_list for item in sublist]

python3 -m http.server 8000

numbers[::-1]

import math; fact_5 = math.factorial(5)

even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]  
# [2, 4]

words = ['this', 'is', 'a', 'list', 'of', 'words']
max(words, key=len)
# 'words'

li = [num for num in range(0,100)]  
# this will create a list of numbers from 0 to 99

num_set = { num for num in range(0,100)}  
# this will create a set of numbers from 0 to 99


dict_numbers = {x:x*x for x in range(1,5) }  
# {1: 1, 2: 4, 3: 9, 4: 16}

print("even") if 4%2==0 else print("odd")

while 1:0

isinstance(2, int)  
isinstance("allwin", str)  
isinstance([3,4,1997], list)

a=5  
while a > 0: a = a - 1; print(a)

print("Hello, World!", file=open('file.txt', 'w'))

print("umbrella".count('l'))# 2

list1.extend(list2)# contents of list 2 will be added to the list1

dict1.update(dict2)  
# contents of dictionary 2 will be added to the dictionary 1

set1.update(set2)  
# contents of set2 will be copied to the set1

import time; print(time.time())

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]  
most_frequent_element = max(set(test_list), key=test_list.count)  
# 4

However, this is not efficient and we can do the same using the collections module in a more efficient way like this.

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]  
  
from collections import Counter  
print(Counter(numbers).most_common()[0][0]) # 4

numbers = [[num] for num in range(10)]  
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]

print(int('30', 8))   
# 24

dict(name='allwin', age=23)

quotient, remainder = divmod(4,5)

list(set([4, 4, 5, 5, 6]))

First, let us sort the list using the sorted() method. The sorted method will **return the sorted list**.

sorted([5, 2, 9, 1])# [1, 2, 5, 9]

Next, let us sort this using the sort() method. The sort() method will sort the original list and not return anything.

li = [5, 2, 9, 1]  
li.sort()  
  
print(li)  
# 1, 2, 5, 9

sorted([5, 2, 9, 1], reverse=True)# [9, 5, 2, 1]

import string; print(string.ascii_lowercase)  
# abcdefghijklmnopqrstuvwxyz

import string; print(string.ascii_uppercase)  
# ABCDEFGHIJKLMNOPQRSTUVWXYZ

import string; print(string.digits)  
# 0123456789

print(int('da9', 16))  
# 3497

import time; print(time.ctime())  
# Thu Aug 13 20:16:23 2020

list(map(int, ['1', '2', '3']))  
# [1, 2, 3]

# d = {'five': 5, 'one': 1, 'four': 4, 'eight': 8}  
{key:d[key] for key in sorted(d.keys())}  
# {'eight': 8, 'five': 5, 'four': 4, 'one': 1}

# x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}  
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}  
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

# li = [1,2,3,4,5] # right to left  
li[n:] + li[:n] # n is the no of rotations  
li[2:] + li[:2]  
[3, 4, 5, 1, 2]# left to right  
li[-n:] + li[:-n]  
li[-1:] + li[:-1]   
[5, 1, 2, 3, 4]

''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))  
# abcdeffgvcg

list(list(x) for x in zip(*old_list))  
# old_list = [[1, 2, 3], [3, 4, 6], [5, 6, 7]]  
# [[1, 3, 5], [2, 4, 6], [3, 6, 7]]


list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] ))  
# [2, 4, 6]

a, *b, c = [1, 2, 3, 4, 5]  
print(a) # 1  
print(b) # [2, 3, 4]  
print(c) # 5


2. 2進数から10進数へ

decimal = int('1010', 2)  
print(decimal) #10


3.小文字に変換する

"Hi my name is Allwin".lower() 
# 'hi my name is allwin'  

"Hi my name is Allwin".casefold()  
# 'hi my name is allwin'


4.大文字に変換する

"hi my name is Allwin".upper()  
# 'HI MY NAME IS ALLWIN'


5. 文字列からバイト型への変換

"convert string to bytes using encode method".encode()  
# b'convert string to bytes using encode method'


6. ドキュメントをコピーする

import shutil; shutil.copyfile('source.txt', 'dest.txt')


7. クイックソート

qsort = lambda l : l if len(l)<=1 else qsort([x for x in l[1:] if x < l[0]]) + [l[0]] + qsort([x for x in l[1:] if x >= l[0]])


8. 連続するn個の数値の和

sum(range(0, n+1))

This is not efficient and we can do the same using the formula below.

sum_n = n*(n+1)//2


9. 課題交換

a,b = b,a


10. フィボナッチ数列

fib = lambda x: x if x<=1 else fib(x-1) + fib(x-2) # The correct Fibonacci series function
fib(8) # The result should be 21


11. ネストしたリストを1つのリストに統合する

[item for sublist in main_list for item in sublist]


12. HTTPサービスの実行

python3 -m http.server 8000


13. 反転リスト

numbers[::-1]


14. ある数の因数を求めよ

import math; fact_5 = math.factorial(5)


15. for" と "if" を使ったリスト解析。

even_list = [number for number in [1, 2, 3, 4] if number % 2 == 0]  
# [2, 4]


16. リストから最も長い文字列を取得する

words = ['this', 'is', 'a', 'list', 'of', 'words']
max(words, key=len)
# 'words'


17. 誘導体リスト

li = [num for num in range(0,100)]  
# this will create a list of numbers from 0 to 99


18.セット導出

num_set = { num for num in range(0,100)}  
# this will create a set of numbers from 0 to 99


19.辞書の導出

dict_numbers = {x:x*x for x in range(1,5) }  
# {1: 1, 2: 4, 3: 9, 4: 16}


20. if-else

print("even") if 4%2==0 else print("odd")


21.無限ループ

while 1:0


22. データ型を確認する

isinstance(2, int)  
isinstance("allwin", str)  
isinstance([3,4,1997], list)


23. while ループ

a=5  
while a > 0: a = a - 1; print(a)


24. ファイルへの書き込みに "print()"を使用する

print("Hello, World!", file=open('file.txt', 'w'))


25. 文字列中のある文字の頻度を計算する

print("umbrella".count('l'))# 2


26. 2つのリストをマージする

list1.extend(list2)# contents of list 2 will be added to the list1


27. 2つの辞書をマージする

dict1.update(dict2)  
# contents of dictionary 2 will be added to the dictionary 1


28. 2つのコレクションをマージする

set1.update(set2)  
# contents of set2 will be copied to the set1


29. タイムスタンプ

import time; print(time.time())


30. 最も頻出する要素

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]  
most_frequent_element = max(set(test_list), key=test_list.count)  
# 4

However, this is not efficient and we can do the same using the collections module in a more efficient way like this.

numbers = [9, 4, 5, 4, 4, 5, 9, 5, 4]  
  
from collections import Counter  
print(Counter(numbers).most_common()[0][0]) # 4


31. ネストされたリスト誘導体

numbers = [[num] for num in range(10)]  
# [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]


32. 8進数から10進数へ

print(int('30', 8))   
# 24


33. キー・バリュー・ペアを辞書に変換する

dict(name='allwin', age=23)


34. 商と余りを計算する

quotient, remainder = divmod(4,5)


35. リストから重複する要素を削除する

list(set([4, 4, 5, 5, 6]))


36. リストを昇順にソートする

First, let us sort the list using the sorted() method. The sorted method will **return the sorted list**.

sorted([5, 2, 9, 1])# [1, 2, 5, 9]

Next, let us sort this using the sort() method. The sort() method will sort the original list and not return anything.

li = [5, 2, 9, 1]  
li.sort()  
  
print(li)  
# 1, 2, 5, 9


37. リストを降順でソートする

sorted([5, 2, 9, 1], reverse=True)# [9, 5, 2, 1]


38. 小文字の文字列を取得する

import string; print(string.ascii_lowercase)  
# abcdefghijklmnopqrstuvwxyz


39. 大文字の文字列を取得する

import string; print(string.ascii_uppercase)  
# ABCDEFGHIJKLMNOPQRSTUVWXYZ


40. 0から9までの数字を文字列型で取得する

import string; print(string.digits)  
# 0123456789


41. 16進数から10進数へ

print(int('da9', 16))  
# 3497


42. 人間が読みやすい日付時間

import time; print(time.ctime())  
# Thu Aug 13 20:16:23 2020


43. リスト要素の文字列型から整数型に変換する

list(map(int, ['1', '2', '3']))  
# [1, 2, 3]


44. 辞書を"key"でソートする。

# d = {'five': 5, 'one': 1, 'four': 4, 'eight': 8}  
{key:d[key] for key in sorted(d.keys())}  
# {'eight': 8, 'five': 5, 'four': 4, 'one': 1}


45. 辞書を"value"でソートしてください。

# x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}  
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}  
# {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}


46.リストを回転させる

# li = [1,2,3,4,5] # right to left  
li[n:] + li[:n] # n is the no of rotations  
li[2:] + li[:2]  
[3, 4, 5, 1, 2]# left to right  
li[-n:] + li[:-n]  
li[-1:] + li[:-1]   
[5, 1, 2, 3, 4]


47. 文字列から数字を削除する

''.join(list(filter(lambda x: x.isalpha(), 'abc123def4fg56vcg2')))  
# abcdeffgvcg


48. 転置行列

list(list(x) for x in zip(*old_list))  
# old_list = [[1, 2, 3], [3, 4, 6], [5, 6, 7]]  
# [[1, 3, 5], [2, 4, 6], [3, 6, 7]]



49. リストから偶数をフィルタリングする

list(filter(lambda x: x%2 == 0, [1, 2, 3, 4, 5, 6] ))  
# [2, 4, 6]


50. 開梱作業

a, *b, c = [1, 2, 3, 4, 5]  
print(a) # 1  
print(b) # [2, 3, 4]  
print(c) # 5


Translated from: https://link.zhihu.com/?target=https%3A//allwin-raju-12.medium.com/50-python-one-liners-everyone-should-know-182ea7c8de9d