코드 효율을 높이는python 기술 10개
namedtuple
If you are too lazy to create a class but you still want to use a variable that can act as a class object, then you should use namedtuple: from collections import namedtuple
user = namedtuple('u', [1, 2, 3])
ztq = user(a='a', b='b',c='c')
print(ztq.a, ztq.b, ztq.c)
result: (1,2,3)
decorator
If you are too lazy to change a function from inner code but you still want to add some new features to a function, you should use decorator. For example, if you want to print “hello” when you add two numbers: def hello(fn):
def wrapper(*args, **kwargs):
aa = fn(*args, **kwargs)
print('hello')
return aa
return wrapper
def my_add(a,b):
return a+b
my_add = hello(my_add)
aa = my_add(10,10)
print(aa)
result: hello
20
or you can use operator “@” to implement your function elegantly: def hello(fn):
def wrapper(*args, **kwargs):
aa = fn(*args, **kwargs)
print('hello')
return aa
return wrapper
@hello
def my_add(a,b):
return a+b
aa = my_add(10,10)
print(aa)
enumerate
If you are too lazy to count the index of a list in a loop but you still need the index, then you shoud use enumerate: a = ['a', 'b', 'c']
for ind, item in a:
print(ind, item)
result: (0, 'a')
(1, 'b')
(2, 'c')
iterator
If you are too lazy to get the every elements in a list by index or “for” loop but you still need to get every element in order, then you should use iterator: def inc():
for i in range(10):
yield i
x = inc()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
result: 0
1
2
3
4
5
6
7
Do not easily copy object in python
If you are too lazy to get deepcopy a other oject but you still want get a copy of a exists one, then you many creating a bug in you program! In python, all things are objects, even class is a kind of object. If you want to copy a object another object, then the ID of two objects are same which means the two objects are. If you modify one object, then another object are also modified. class sample:
def __init__(self, items = []):
self.items = items
def append(self, value):
self.items.append(value)
s1 = sample(items=['1'])
s2 = s1
s1.append('a')
s2.append('b')
print(s1.items, s2.items)
result: (['1', 'a', 'b'], ['1', 'a', 'b'])
another example: a = [1,2,3,4]
b = a
b[0] = 100
print(a)
print(b)
result: [100,2,3,4]
[100,2,3,4]
Instead, you should use “deepcopy” to copy two objects a = [1,2,3,4]
b = copy.deepcopy(a)
b[0] = 100
print(a)
print(b)
result: [1,2,3,4]
[100,2,3,4]
itertools
If you are too lazy to write a infinite loop in an iterator but you still want to reset to loop in iterator, then you should use itertools: import itertools
def inc():
a = [1,2,3,4,5]
cs = itertools.cycle(a)
for i in cs:
yield i
x = inc()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
result: 1
2
3
4
5
1
2
3
concurrent.futures
If you are too lazy to write a multi-thread to process all the elements of a list which may cost lots of time, then you should use a python build-in multi-thread tools: import concurrent.futures
def print_num(num):
print(num)
a = range(5)
with concurrent.futures.ProcessPoolExecutor() as executor:
executor.map(load_and_resize, a)
result: 0
1
2
3
4
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSON
JSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다.
그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다.
저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
from collections import namedtuple
user = namedtuple('u', [1, 2, 3])
ztq = user(a='a', b='b',c='c')
print(ztq.a, ztq.b, ztq.c)
(1,2,3)
If you are too lazy to change a function from inner code but you still want to add some new features to a function, you should use decorator. For example, if you want to print “hello” when you add two numbers:
def hello(fn):
def wrapper(*args, **kwargs):
aa = fn(*args, **kwargs)
print('hello')
return aa
return wrapper
def my_add(a,b):
return a+b
my_add = hello(my_add)
aa = my_add(10,10)
print(aa)
result:
hello
20
or you can use operator “@” to implement your function elegantly:
def hello(fn):
def wrapper(*args, **kwargs):
aa = fn(*args, **kwargs)
print('hello')
return aa
return wrapper
@hello
def my_add(a,b):
return a+b
aa = my_add(10,10)
print(aa)
enumerate
If you are too lazy to count the index of a list in a loop but you still need the index, then you shoud use enumerate: a = ['a', 'b', 'c']
for ind, item in a:
print(ind, item)
result: (0, 'a')
(1, 'b')
(2, 'c')
iterator
If you are too lazy to get the every elements in a list by index or “for” loop but you still need to get every element in order, then you should use iterator: def inc():
for i in range(10):
yield i
x = inc()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
result: 0
1
2
3
4
5
6
7
Do not easily copy object in python
If you are too lazy to get deepcopy a other oject but you still want get a copy of a exists one, then you many creating a bug in you program! In python, all things are objects, even class is a kind of object. If you want to copy a object another object, then the ID of two objects are same which means the two objects are. If you modify one object, then another object are also modified. class sample:
def __init__(self, items = []):
self.items = items
def append(self, value):
self.items.append(value)
s1 = sample(items=['1'])
s2 = s1
s1.append('a')
s2.append('b')
print(s1.items, s2.items)
result: (['1', 'a', 'b'], ['1', 'a', 'b'])
another example: a = [1,2,3,4]
b = a
b[0] = 100
print(a)
print(b)
result: [100,2,3,4]
[100,2,3,4]
Instead, you should use “deepcopy” to copy two objects a = [1,2,3,4]
b = copy.deepcopy(a)
b[0] = 100
print(a)
print(b)
result: [1,2,3,4]
[100,2,3,4]
itertools
If you are too lazy to write a infinite loop in an iterator but you still want to reset to loop in iterator, then you should use itertools: import itertools
def inc():
a = [1,2,3,4,5]
cs = itertools.cycle(a)
for i in cs:
yield i
x = inc()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
result: 1
2
3
4
5
1
2
3
concurrent.futures
If you are too lazy to write a multi-thread to process all the elements of a list which may cost lots of time, then you should use a python build-in multi-thread tools: import concurrent.futures
def print_num(num):
print(num)
a = range(5)
with concurrent.futures.ProcessPoolExecutor() as executor:
executor.map(load_and_resize, a)
result: 0
1
2
3
4
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSON
JSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다.
그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다.
저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
a = ['a', 'b', 'c']
for ind, item in a:
print(ind, item)
(0, 'a')
(1, 'b')
(2, 'c')
If you are too lazy to get the every elements in a list by index or “for” loop but you still need to get every element in order, then you should use iterator:
def inc():
for i in range(10):
yield i
x = inc()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
result:
0
1
2
3
4
5
6
7
Do not easily copy object in python
If you are too lazy to get deepcopy a other oject but you still want get a copy of a exists one, then you many creating a bug in you program! In python, all things are objects, even class is a kind of object. If you want to copy a object another object, then the ID of two objects are same which means the two objects are. If you modify one object, then another object are also modified. class sample:
def __init__(self, items = []):
self.items = items
def append(self, value):
self.items.append(value)
s1 = sample(items=['1'])
s2 = s1
s1.append('a')
s2.append('b')
print(s1.items, s2.items)
result: (['1', 'a', 'b'], ['1', 'a', 'b'])
another example: a = [1,2,3,4]
b = a
b[0] = 100
print(a)
print(b)
result: [100,2,3,4]
[100,2,3,4]
Instead, you should use “deepcopy” to copy two objects a = [1,2,3,4]
b = copy.deepcopy(a)
b[0] = 100
print(a)
print(b)
result: [1,2,3,4]
[100,2,3,4]
itertools
If you are too lazy to write a infinite loop in an iterator but you still want to reset to loop in iterator, then you should use itertools: import itertools
def inc():
a = [1,2,3,4,5]
cs = itertools.cycle(a)
for i in cs:
yield i
x = inc()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
result: 1
2
3
4
5
1
2
3
concurrent.futures
If you are too lazy to write a multi-thread to process all the elements of a list which may cost lots of time, then you should use a python build-in multi-thread tools: import concurrent.futures
def print_num(num):
print(num)
a = range(5)
with concurrent.futures.ProcessPoolExecutor() as executor:
executor.map(load_and_resize, a)
result: 0
1
2
3
4
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSON
JSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다.
그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다.
저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
class sample:
def __init__(self, items = []):
self.items = items
def append(self, value):
self.items.append(value)
s1 = sample(items=['1'])
s2 = s1
s1.append('a')
s2.append('b')
print(s1.items, s2.items)
(['1', 'a', 'b'], ['1', 'a', 'b'])
a = [1,2,3,4]
b = a
b[0] = 100
print(a)
print(b)
[100,2,3,4]
[100,2,3,4]
a = [1,2,3,4]
b = copy.deepcopy(a)
b[0] = 100
print(a)
print(b)
[1,2,3,4]
[100,2,3,4]
If you are too lazy to write a infinite loop in an iterator but you still want to reset to loop in iterator, then you should use itertools:
import itertools
def inc():
a = [1,2,3,4,5]
cs = itertools.cycle(a)
for i in cs:
yield i
x = inc()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
result:
1
2
3
4
5
1
2
3
concurrent.futures
If you are too lazy to write a multi-thread to process all the elements of a list which may cost lots of time, then you should use a python build-in multi-thread tools: import concurrent.futures
def print_num(num):
print(num)
a = range(5)
with concurrent.futures.ProcessPoolExecutor() as executor:
executor.map(load_and_resize, a)
result: 0
1
2
3
4
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSON
JSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다.
그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다.
저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
import concurrent.futures
def print_num(num):
print(num)
a = range(5)
with concurrent.futures.ProcessPoolExecutor() as executor:
executor.map(load_and_resize, a)
0
1
2
3
4
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.