def foolish_range():
for i in [0, 1, 2, 3, 4, 5]:
print i**2
def middle_range(n=10000000):
for i in range(n):
pass
# print i**2
def advanced_range(n=10000000):
for i in xrange(n):
pass
# print i**2
foolish_range()
0 1 4 9 16 25
middle_range()
advanced_range()
%timeit foolish_range
10000000 loops, best of 3: 28.8 ns per loop
%timeit middle_range
10000000 loops, best of 3: 27.7 ns per loop
%timeit advanced_range
10000000 loops, best of 3: 27.8 ns per loop
%timeit middle_range, 1000000000
10000000 loops, best of 3: 58.8 ns per loop
%timeit advanced_range, 1000000000
10000000 loops, best of 3: 58.6 ns per loop
colors = ['red', 'green', 'blue', 'yellow']
for i in range(len(colors)):
print colors[i]
red green blue yellow
for color in colors:
print color
red green blue yellow
for i in range(len(colors)-1, -1, -1):
print colors[i]
yellow blue green red
for color in reversed(colors):
print color
yellow blue green red
for i in range(len(colors)):
print i, '-->', colors[i]
0 --> red 1 --> green 2 --> blue 3 --> yellow
for i, color in enumerate(colors):
print i, '-->', color
0 --> red 1 --> green 2 --> blue 3 --> yellow
names = ['근영', '으리 파이썬', '파이썬을 활용한 데이터분석 엄청 어려워!!']
colors
['red', 'green', 'blue', 'yellow']
n = min(len(names), len(colors))
# 한글이라 인코딩 때문에 커지네.
len(names[0])
6
n
3
for i in range(n):
print names[i], '-->', colors[i]
근영 --> red 으리 파이썬 --> green 파이썬을 활용한 데이터분석 엄청 어려워!! --> blue
zip(names, colors)
[('\xea\xb7\xbc\xec\x98\x81', 'red'), ('\xec\x9c\xbc\xeb\xa6\xac \xed\x8c\x8c\xec\x9d\xb4\xec\x8d\xac', 'green'), ('\xed\x8c\x8c\xec\x9d\xb4\xec\x8d\xac\xec\x9d\x84 \xed\x99\x9c\xec\x9a\xa9\xed\x95\x9c \xeb\x8d\xb0\xec\x9d\xb4\xed\x84\xb0\xeb\xb6\x84\xec\x84\x9d \xec\x97\x84\xec\xb2\xad \xec\x96\xb4\xeb\xa0\xa4\xec\x9b\x8c!!', 'blue')]
for name, color in zip(names, colors):
print name, '-->', color
근영 --> red 으리 파이썬 --> green 파이썬을 활용한 데이터분석 엄청 어려워!! --> blue
izip(names, colors)
<itertools.izip at 0x1032a9ab8>
# iteration으로 만들어줘서 메모리 절약
from itertools import izip
for name, color in izip(names, colors):
print name, '-->', color
근영 --> red 으리 파이썬 --> green 파이썬을 활용한 데이터분석 엄청 어려워!! --> blue
colors
['red', 'green', 'blue', 'yellow']
for color in sorted(colors):
print color
blue green red yellow
for color in sorted(colors, reverse=True):
print color
yellow red green blue
colors
['red', 'green', 'blue', 'yellow']
def compare_length(c1, c2):
if len(c1) < len(c2):
return -1
if len(c1) > len(c2):
return 1
return 0
print sorted(colors, cmp=compare_length)
['red', 'blue', 'green', 'yellow']
print sorted(colors, key=len)
['red', 'blue', 'green', 'yellow']
sorted?
Type: builtin_function_or_method
String form: <built-in function sorted>
Namespace: Python builtin
Docstring: sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ]
# 리스트 삽입 순서
print student_tuples
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
# student_tuples의 2번째인 10, 12, 15 순서
print sorted(student_tuples, key=lambda student: student[2])
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
%%writefile test_txt.txt
Python for data analysis is very difficult.
I do not understand well.
Overwriting test_txt.txt
f = open('test_txt.txt')
blocks = []
while True:
# 32자 기준으로 파일을 읽으며
block = f.read(32)
# 파일의 끝에 오면 루프 종료
if block == '':
break
# 32자는 blocks 리스트에 추가한다.
blocks.append(block)
blocks
['Python for data analysis is very', ' difficult.\nI do not understand ', 'well.']
blocks = []
f = open('test_txt.txt')
from functools import partial
# partial로 f.read로 32자를 읽고 끝인가? 끝이 아니면 계속 loop
# 아니면 block으로 32자를 넘기고 blocks에 추가
# 음? for문을 while처럼 사용할 수 있다니!
for block in iter(partial(f.read, 32), ''):
blocks.append(block)
blocks
['Python for data analysis is very', ' difficult.\nI do not understand ', 'well.']
partial?
Type: type
String form: <type 'functools.partial'>
File: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/functools.py
Docstring:
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
def foolish_find(seq, target):
found = False
for i, value in enumerate(seq):
if value == target:
found = True
break
if not found:
return -1
return i
def advanced_find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return i
seq = 'I love Python. Python is very easy'.split()
seq
['I', 'love', 'Python.', 'Python', 'is', 'very', 'easy']
foolish_find(seq, 'easy')
6
advanced_find(seq, 'easy')
6
# x가 3일때 break 문으로 빠져 나오기 때문에 끝!
for x in range(0, 5):
print x
if x == 3:
break
else:
print 'else'
0 1 2 3
# x가 6이 될리가 없으므로 break로 for문을 빠져나올 수 없다.
# for문이 끝나고 else문이 실행이 된다.
for x in range(0, 5):
print x
if x == 6:
break
else:
print 'else'
0 1 2 3 4 else
# 이거랑 뭔 차이냐??
# else 없이 써도 되는데?!
# 조금 더 생각해보니
for x in range(0, 5):
print x
if x == 6:
break
print 'else'
0 1 2 3 4 else
for x in range(0, 5):
print x
if x == 3:
break
print 'else문 안 썼을 경우는 break 되든지 말든지 상관없이 무조건 실행'
0 1 2 3 else문 안 썼을 경우는 break 되든지 말든지 상관없이 무조건 실행
for x in range(0, 5):
print x
if x == 3:
break
else:
print 'else문을 썼을 경우는 break 되면 실행 안됨'
0 1 2 3
d = {'niceguy': 'blue', 'python': 'green', 'geunyoung': 'red'}
for k in d:
print k
python geunyoung niceguy
for k in d.keys():
if k.startswith('n'):
del d[k]
d
{'geunyoung': 'red', 'python': 'green'}
d = {'niceguy': 'blue', 'python': 'green', 'geunyoung': 'red'}
# 처음에는 이게 훨씬 더 어려워 보인다.
# 그냥 저 위에 것을 이렇게 축약(?)한 것이라고 생각하면 된다.
# 근데 나도 코드 짤때는 위의 방법을 사용해서 짜는데..
# for k in d에서 k를 먼저 추출
# if not k.startswith('n')
# k : d[k] 이것을 d에 할당
d = {k : d[k] for k in d if not k.startswith('n')}
d
{'geunyoung': 'red', 'python': 'green'}
# key: value
# geunyoung이 key이고 d['geunyoung']이 value(red)
d2 = {'geunyoung': d['geunyoung']}
d2
{'geunyoung': 'red'}
# 이것도 C 쓰던 사람들이 많이 사용하는 방법
# 물어보면 밑의 방법보다 이게 훨씬 편하다고 한다.
for k in d:
print k, '-->', d[k]
python --> green geunyoung --> red
for k, v in d.items():
print k, '-->', v
python --> green geunyoung --> red
for k, v in d.iteritems():
print k, '-->', v
python --> green geunyoung --> red
names
['\xea\xb7\xbc\xec\x98\x81', '\xec\x9c\xbc\xeb\xa6\xac \xed\x8c\x8c\xec\x9d\xb4\xec\x8d\xac', '\xed\x8c\x8c\xec\x9d\xb4\xec\x8d\xac\xec\x9d\x84 \xed\x99\x9c\xec\x9a\xa9\xed\x95\x9c \xeb\x8d\xb0\xec\x9d\xb4\xed\x84\xb0\xeb\xb6\x84\xec\x84\x9d \xec\x97\x84\xec\xb2\xad \xec\x96\xb4\xeb\xa0\xa4\xec\x9b\x8c!!']
colors = ['red', 'green', 'blue']
d = dict(izip(names, colors))
for k, v in d.items():
print k, v
으리 파이썬 green 근영 red 파이썬을 활용한 데이터분석 엄청 어려워!! blue
enumerate(names)
<enumerate at 0x1032949b0>
# iterator 형식을 list로 추출해 보기
list(enumerate(names))
[(0, '\xea\xb7\xbc\xec\x98\x81'), (1, '\xec\x9c\xbc\xeb\xa6\xac \xed\x8c\x8c\xec\x9d\xb4\xec\x8d\xac'), (2, '\xed\x8c\x8c\xec\x9d\xb4\xec\x8d\xac\xec\x9d\x84 \xed\x99\x9c\xec\x9a\xa9\xed\x95\x9c \xeb\x8d\xb0\xec\x9d\xb4\xed\x84\xb0\xeb\xb6\x84\xec\x84\x9d \xec\x97\x84\xec\xb2\xad \xec\x96\xb4\xeb\xa0\xa4\xec\x9b\x8c!!')]
d = dict(enumerate(names))
for k, v in d.items():
print k, v
0 근영 1 으리 파이썬 2 파이썬을 활용한 데이터분석 엄청 어려워!!
colors = ['red', 'green', 'red', 'blue', 'green', 'red']
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] += 1
d
{'blue': 1, 'green': 2, 'red': 3}
d = {}
for color in colors:
d[color] = d.get(color, 0) + 1
d
{'blue': 1, 'green': 2, 'red': 3}
# 기본값이 0인 사전을 얻는 방법
from collections import defaultdict
d = defaultdict(int)
d
defaultdict(<type 'int'>, {})
for color in colors:
d[color] += 1
d
defaultdict(<type 'int'>, {'blue': 1, 'green': 2, 'red': 3})
for k, v in d.items():
print k, v
blue 1 green 2 red 3
type(d)
collections.defaultdict
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)
d
{5: ['roger', 'betty'], 6: ['rachel', 'judith'], 7: ['raymond', 'matthew', 'melissa', 'charlie']}
d = {}
for name in names:
key = len(name)
d.setdefault(key, []).append(name)
d
{5: ['roger', 'betty'], 6: ['rachel', 'judith'], 7: ['raymond', 'matthew', 'melissa', 'charlie']}
d = defaultdict(list)
for name in names:
key = len(name)
d[key].append(name)
d
defaultdict(<type 'list'>, {5: ['roger', 'betty'], 6: ['rachel', 'judith'], 7: ['raymond', 'matthew', 'melissa', 'charlie']})
type(d)
collections.defaultdict
type(d[0])
list
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
while d:
key, value = d.popitem()
print key, '-->', value
matthew --> blue rachel --> green raymond --> red
d
{}
defaults = {'color': 'red', 'user': 'guest'}
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
_StoreAction(option_strings=['-u', '--user'], dest='user', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
parser.add_argument('-c', '--color')
_StoreAction(option_strings=['-c', '--color'], dest='color', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
namespace = parser.parse_args([])
command_line_args = {k:v for k, v in vars(namespace).items() if v}
command_line_args
{}
d = defaults.copy()
d
{'color': 'red', 'user': 'guest'}
import os
d.update(os.environ)
# d
d.update(command_line_args)
# d
# Python 3.3 버전부터 지원이네..
# import collections.ChainMap
# d = ChainMap(command_line_args, os.environ, defaults)
# twitter_search('@obama', False, 20, True)
# 확실히 앞의 글자는 obama를 찾는다는 것을 알겠고
# 뒤의 인자가 무엇인지 모를텐데 keyword를 붙여주니 코드 가독성이 높아지네
# twitter_search('@obama', retweets=False, numtweets=20, popular=True)
# doctest.testmod()
# doctest.testmod()
# TestResults(failed=0, attempted=4)
# TestResults = namedtuple('TestResults', ['failed', 'attempted'])
p = 'Raymond', 'Heittinger', 0x30, 'python@example.com'
p
('Raymond', 'Heittinger', 48, 'python@example.com')
type(p)
tuple
fname = p[0]
lname = p[1]
age = p[2]
email = p[3]
fname, lname, age, email
('Raymond', 'Heittinger', 48, 'python@example.com')
del fname, lname, age, email
fname, lname, age, email = p
fname, lname, age, email
('Raymond', 'Heittinger', 48, 'python@example.com')
def temp_fibonacci(n):
x = 0
y = 1
for i in range(n):
print x
t = y
y = x + y
x = t
def unpack_fibonacci(n):
x, y = 0, 1
for i in range(n):
print x
# y가 x로, x+y가 y로
x, y = y, x+y
temp_fibonacci(10)
0 1 1 2 3 5 8 13 21 34
unpack_fibonacci(10)
0 1 1 2 3 5 8 13 21 34
tmp_x = x + dx * t
tmp_y = y + dy * t
tmp_dx = influence(m, x, y, dx, dy, partial='x')
tmp_dy = influence(m, x, y, dx, dy, partial='y')
x = tmp_x
y = tmp_y
dx = tmp_dx
dy = tmp_dy
x, y, dx, dy = (x + dx * t,
y + dy * t,
influence(m, x, y, dx, dy, partial='x'),
influence(,m x, y, dx, dy, partial='y'))
names
['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie']
s = names[0]
for name in names[1:]:
s += ', ' + name
print s
raymond, rachel, matthew, roger, betty, melissa, judith, charlie
# join이 정말 편해서 위의 방법은 도저히 못 쓰겠다..
print ', '.join(names)
raymond, rachel, matthew, roger, betty, melissa, judith, charlie
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
names
['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie']
del names[0]
names
['rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie']
names.pop(0)
'rachel'
names
['matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie']
names.insert(0, 'mark')
names
['mark', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie']
from collections import deque
names = deque(['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie'])
names
deque(['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie'])
type(names)
collections.deque
del names[0]
names
deque(['rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie'])
names.popleft()
'rachel'
names
deque(['matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie'])
names.appendleft('mark')
names
deque(['mark', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie'])
names.append('end')
names
deque(['mark', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie', 'end'])
deque.append deque.count deque.maxlen deque.popleft deque.rotate
deque.appendleft deque.extend deque.mro deque.remove
deque.clear deque.extendleft deque.pop deque.reverse
import urllib
def web_lookup(url, saved={}):
if url in saved:
return saved[url]
page = urllib.urlopen(url).read()
saved[url] = page
return page
from functools import wraps
def cache(func):
saved = {}
@wraps(func)
def newfunc(*args):
if args in saved:
# Here is bug
return newfunc(*args)
result = func(*args)
saved[args] = result
return result
return newfunc
from functools import wraps
def cache2(func):
saved = {}
@wraps(func)
def newfunc(*args):
if args in saved:
return saved[args]
result = func(*args)
saved[args] = result
return result
return newfunc
@cache
def web_lookup2(url):
return urllib.urlopen(url).read()
@cache2
def web_lookup3(url):
return urllib.urlopen(url).read()
url = 'http://naver.com'
print web_lookup(url)[:100]
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Script-Type
print web_lookup2(url)[:100]
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Script-Type
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-361-27ac44ec7929> in <module>()
----> 1 print web_lookup2(url)[:100]
<ipython-input-355-887374cafa10> in newfunc(*args)
6 def newfunc(*args):
7 if args in saved:
----> 8 return newfunc(*args)
9 result = func(*args)
10 saved[args] = result
RuntimeError: maximum recursion depth exceeded in cmp
# Ok! 버그 해결!
# 근데 saved를 계속 저장하고 있나보네..?
print web_lookup3(url)[:100]
<!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Script-Type
# context: 환경설정
from decimal import getcontext
old_context = getcontext().copy()
old_context
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[Overflow, InvalidOperation, DivisionByZero])
getcontext?
Returns this thread's context.
If this thread does not yet have a context, returns
a new context and sets this thread's context.
New contexts are copies of DefaultContext.
getcontext().prec = 50
from decimal import Decimal, setcontext
print Decimal(355) / Decimal(113)
3.1415929203539823008849557522123893805309734513274
setcontext(old_context)
print Decimal(355) / Decimal(113)
3.141592920353982300884955752
from decimal import localcontext, Context
with localcontext(Context(prec=50)):
print Decimal(355) / Decimal(113)
3.1415929203539823008849557522123893805309734513274
with localcontext():
print Decimal(355) / Decimal(113)
3.141592920353982300884955752
print Decimal(355) / Decimal(113)
3.141592920353982300884955752
%%writefile data.txt
test data.txt
Are you sure?
Overwriting data.txt
f = open('data.txt')
try:
data = f.read()
finally:
f.close()
data
'test data.txt\nAre you sure?'
data = ''
with open('data.txt') as f:
data = f.read()
data
'test data.txt\nAre you sure?'
with open('data2.txt') as f:
data = f.read()
--------------------------------------------------------------------------- IOError Traceback (most recent call last) <ipython-input-184-adb48fd02705> in <module>() ----> 1 with open('data2.txt') as f: 2 data = f.read() IOError: [Errno 2] No such file or directory: 'data2.txt'
import threading
# Make a lock
lock = threading.Lock()
# Old-way to use a lock
lock.acquire()
try:
print 'Critical section 1'
print 'Critical section 2'
finally:
lock.release()
Critical section 1 Critical section 2
# New-way to use a lock
with lock:
print 'Critical section 1'
print 'Critical section 2'
Critical section 1 Critical section 2
try:
os.remove('somefile.tmp')
except OSError:
pass
from contextlib import contextmanager
@contextmanager
def ignored(*exceptions):
try:
yield
except exceptions:
pass
with ignored(OSError):
os.remove('somefile.tmp')
@contextmanager
def ignored(*exceptions):
try:
yield
except exceptions:
pass
import sys
with open('help.txt', 'w') as f:
oldstdout = sys.stdout
sys.stdout = f
try:
help(pow)
finally:
sys.stdout = oldstdout
help(pow)
Help on built-in function pow in module __builtin__: pow(...) pow(x, y[, z]) -> number With two arguments, equivalent to x**y. With three arguments, equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
!cat help.txt
Help on built-in function pow in module __builtin__: pow(...) pow(x, y[, z]) -> number With two arguments, equivalent to x**y. With three arguments, equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
from contextlib import redirect_stdout
with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-196-0af051e507b4> in <module>() ----> 1 from contextlib import redirect_stdout 2 with open('help.txt', 'w') as f: 3 with redirect_stdout(f): 4 help(pow) ImportError: cannot import name redirect_stdout
import sys
from contextlib import contextmanager
@contextmanager
def redirect_stdout(new_target):
old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
try:
yield new_target # run some code with the replaced stdout
finally:
sys.stdout = old_target # restore to the previous value
with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(sqrt)
!cat help.txt
Help on ufunc object: sqrt = class ufunc(__builtin__.object) | Functions that operate element by element on whole arrays. | | To see the documentation for a specific ufunc, use np.info(). For | example, np.info(np.sin). Because ufuncs are written in C | (for speed) and linked into Python with NumPy's ufunc facility, | Python's help() function finds this page whenever help() is called | on a ufunc. | | A detailed explanation of ufuncs can be found in the "ufuncs.rst" | file in the NumPy reference guide. | | Unary ufuncs: | ============= | | op(X, out=None) | Apply op to X elementwise | | Parameters | ---------- | X : array_like | Input array. | out : array_like | An array to store the output. Must be the same shape as `X`. | | Returns | ------- | r : array_like | `r` will have the same shape as `X`; if out is provided, `r` | will be equal to out. | | Binary ufuncs: | ============== | op(X, Y, out=None) | Apply `op` to `X` and `Y` elementwise. May "broadcast" to make | the shapes of `X` and `Y` congruent. | | The broadcasting rules are: | | * Dimensions of length 1 may be prepended to either array. | * Arrays may be repeated along dimensions of length 1. | | Parameters | ---------- | X : array_like | First input array. | Y : array_like | Second input array. | out : array_like | An array to store the output. Must be the same shape as the | output would have. | | Returns | ------- | r : array_like | The return value; if out is provided, `r` will be equal to out. | | Methods defined here: | | __call__(...) | x.__call__(...) <==> x(...) | | __repr__(...) | x.__repr__() <==> repr(x) | | __str__(...) | x.__str__() <==> str(x) | | accumulate(...) | accumulate(array, axis=0, dtype=None, out=None) | | Accumulate the result of applying the operator to all elements. | | For a one-dimensional array, accumulate produces results equivalent to:: | | r = np.empty(len(A)) | t = op.identity # op = the ufunc being applied to A's elements | for i in range(len(A)): | t = op(t, A[i]) | r[i] = t | return r | | For example, add.accumulate() is equivalent to np.cumsum(). | | For a multi-dimensional array, accumulate is applied along only one | axis (axis zero by default; see Examples below) so repeated use is | necessary if one wants to accumulate over multiple axes. | | Parameters | ---------- | array : array_like | The array to act on. | axis : int, optional | The axis along which to apply the accumulation; default is zero. | dtype : data-type code, optional | The data-type used to represent the intermediate results. Defaults | to the data-type of the output array if such is provided, or the | the data-type of the input array if no output array is provided. | out : ndarray, optional | A location into which the result is stored. If not provided a | freshly-allocated array is returned. | | Returns | ------- | r : ndarray | The accumulated values. If `out` was supplied, `r` is a reference to | `out`. | | Examples | -------- | 1-D array examples: | | >>> np.add.accumulate([2, 3, 5]) | array([ 2, 5, 10]) | >>> np.multiply.accumulate([2, 3, 5]) | array([ 2, 6, 30]) | | 2-D array examples: | | >>> I = np.eye(2) | >>> I | array([[ 1., 0.], | [ 0., 1.]]) | | Accumulate along axis 0 (rows), down columns: | | >>> np.add.accumulate(I, 0) | array([[ 1., 0.], | [ 1., 1.]]) | >>> np.add.accumulate(I) # no axis specified = axis zero | array([[ 1., 0.], | [ 1., 1.]]) | | Accumulate along axis 1 (columns), through rows: | | >>> np.add.accumulate(I, 1) | array([[ 1., 1.], | [ 0., 1.]]) | | at(...) | at(a, indices, b=None) | | Performs unbuffered in place operation on operand 'a' for elements | specified by 'indices'. For addition ufunc, this method is equivalent to | `a[indices] += b`, except that results are accumulated for elements that | are indexed more than once. For example, `a[[0,0]] += 1` will only | increment the first element once because of buffering, whereas | `add.at(a, [0,0], 1)` will increment the first element twice. | | Parameters | ---------- | a : array_like | The array to perform in place operation on. | indices : array_like or tuple | Array like index object or slice object for indexing into first | operand. If first operand has multiple dimensions, indices can be a | tuple of array like index objects or slice objects. | b : array_like | Second operand for ufuncs requiring two operands. Operand must be | broadcastable over first operand after indexing or slicing. | | Examples | -------- | Set items 0 and 1 to their negative values: | | >>> a = np.array([1, 2, 3, 4]) | >>> np.negative.at(a, [0, 1]) | >>> print(a) | array([-1, -2, 3, 4]) | | :: | | Increment items 0 and 1, and increment item 2 twice: | | >>> a = np.array([1, 2, 3, 4]) | >>> np.add.at(a, [0, 1, 2, 2], 1) | >>> print(a) | array([2, 3, 5, 4]) | | :: | | Add items 0 and 1 in first array to second array, | and store results in first array: | | >>> a = np.array([1, 2, 3, 4]) | >>> b = np.array([1, 2]) | >>> np.add.at(a, [0, 1], b) | >>> print(a) | array([2, 4, 3, 4]) | | outer(...) | outer(A, B) | | Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`. | | Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of | ``op.outer(A, B)`` is an array of dimension M + N such that: | | .. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] = | op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}]) | | For `A` and `B` one-dimensional, this is equivalent to:: | | r = empty(len(A),len(B)) | for i in range(len(A)): | for j in range(len(B)): | r[i,j] = op(A[i], B[j]) # op = ufunc in question | | Parameters | ---------- | A : array_like | First array | B : array_like | Second array | | Returns | ------- | r : ndarray | Output array | | See Also | -------- | numpy.outer | | Examples | -------- | >>> np.multiply.outer([1, 2, 3], [4, 5, 6]) | array([[ 4, 5, 6], | [ 8, 10, 12], | [12, 15, 18]]) | | A multi-dimensional example: | | >>> A = np.array([[1, 2, 3], [4, 5, 6]]) | >>> A.shape | (2, 3) | >>> B = np.array([[1, 2, 3, 4]]) | >>> B.shape | (1, 4) | >>> C = np.multiply.outer(A, B) | >>> C.shape; C | (2, 3, 1, 4) | array([[[[ 1, 2, 3, 4]], | [[ 2, 4, 6, 8]], | [[ 3, 6, 9, 12]]], | [[[ 4, 8, 12, 16]], | [[ 5, 10, 15, 20]], | [[ 6, 12, 18, 24]]]]) | | reduce(...) | reduce(a, axis=0, dtype=None, out=None, keepdims=False) | | Reduces `a`'s dimension by one, by applying ufunc along one axis. | | Let :math:`a.shape = (N_0, ..., N_i, ..., N_{M-1})`. Then | :math:`ufunc.reduce(a, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` = | the result of iterating `j` over :math:`range(N_i)`, cumulatively applying | ufunc to each :math:`a[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`. | For a one-dimensional array, reduce produces results equivalent to: | :: | | r = op.identity # op = ufunc | for i in range(len(A)): | r = op(r, A[i]) | return r | | For example, add.reduce() is equivalent to sum(). | | Parameters | ---------- | a : array_like | The array to act on. | axis : None or int or tuple of ints, optional | Axis or axes along which a reduction is performed. | The default (`axis` = 0) is perform a reduction over the first | dimension of the input array. `axis` may be negative, in | which case it counts from the last to the first axis. | | .. versionadded:: 1.7.0 | | If this is `None`, a reduction is performed over all the axes. | If this is a tuple of ints, a reduction is performed on multiple | axes, instead of a single axis or all the axes as before. | | For operations which are either not commutative or not associative, | doing a reduction over multiple axes is not well-defined. The | ufuncs do not currently raise an exception in this case, but will | likely do so in the future. | dtype : data-type code, optional | The type used to represent the intermediate results. Defaults | to the data-type of the output array if this is provided, or | the data-type of the input array if no output array is provided. | out : ndarray, optional | A location into which the result is stored. If not provided, a | freshly-allocated array is returned. | keepdims : bool, optional | If this is set to True, the axes which are reduced are left | in the result as dimensions with size one. With this option, | the result will broadcast correctly against the original `arr`. | | Returns | ------- | r : ndarray | The reduced array. If `out` was supplied, `r` is a reference to it. | | Examples | -------- | >>> np.multiply.reduce([2,3,5]) | 30 | | A multi-dimensional array example: | | >>> X = np.arange(8).reshape((2,2,2)) | >>> X | array([[[0, 1], | [2, 3]], | [[4, 5], | [6, 7]]]) | >>> np.add.reduce(X, 0) | array([[ 4, 6], | [ 8, 10]]) | >>> np.add.reduce(X) # confirm: default axis value is 0 | array([[ 4, 6], | [ 8, 10]]) | >>> np.add.reduce(X, 1) | array([[ 2, 4], | [10, 12]]) | >>> np.add.reduce(X, 2) | array([[ 1, 5], | [ 9, 13]]) | | reduceat(...) | reduceat(a, indices, axis=0, dtype=None, out=None) | | Performs a (local) reduce with specified slices over a single axis. | | For i in ``range(len(indices))``, `reduceat` computes | ``ufunc.reduce(a[indices[i]:indices[i+1]])``, which becomes the i-th | generalized "row" parallel to `axis` in the final result (i.e., in a | 2-D array, for example, if `axis = 0`, it becomes the i-th row, but if | `axis = 1`, it becomes the i-th column). There are two exceptions to this: | | * when ``i = len(indices) - 1`` (so for the last index), | ``indices[i+1] = a.shape[axis]``. | * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is | simply ``a[indices[i]]``. | | The shape of the output depends on the size of `indices`, and may be | larger than `a` (this happens if ``len(indices) > a.shape[axis]``). | | Parameters | ---------- | a : array_like | The array to act on. | indices : array_like | Paired indices, comma separated (not colon), specifying slices to | reduce. | axis : int, optional | The axis along which to apply the reduceat. | dtype : data-type code, optional | The type used to represent the intermediate results. Defaults | to the data type of the output array if this is provided, or | the data type of the input array if no output array is provided. | out : ndarray, optional | A location into which the result is stored. If not provided a | freshly-allocated array is returned. | | Returns | ------- | r : ndarray | The reduced values. If `out` was supplied, `r` is a reference to | `out`. | | Notes | ----- | A descriptive example: | | If `a` is 1-D, the function `ufunc.accumulate(a)` is the same as | ``ufunc.reduceat(a, indices)[::2]`` where `indices` is | ``range(len(array) - 1)`` with a zero placed | in every other element: | ``indices = zeros(2 * len(a) - 1)``, ``indices[1::2] = range(1, len(a))``. | | Don't be fooled by this attribute's name: `reduceat(a)` is not | necessarily smaller than `a`. | | Examples | -------- | To take the running sum of four successive values: | | >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2] | array([ 6, 10, 14, 18]) | | A 2-D example: | | >>> x = np.linspace(0, 15, 16).reshape(4,4) | >>> x | array([[ 0., 1., 2., 3.], | [ 4., 5., 6., 7.], | [ 8., 9., 10., 11.], | [ 12., 13., 14., 15.]]) | | :: | | # reduce such that the result has the following five rows: | # [row1 + row2 + row3] | # [row4] | # [row2] | # [row3] | # [row1 + row2 + row3 + row4] | | >>> np.add.reduceat(x, [0, 3, 1, 2, 0]) | array([[ 12., 15., 18., 21.], | [ 12., 13., 14., 15.], | [ 4., 5., 6., 7.], | [ 8., 9., 10., 11.], | [ 24., 28., 32., 36.]]) | | :: | | # reduce such that result has the following two columns: | # [col1 * col2 * col3, col4] | | >>> np.multiply.reduceat(x, [0, 3], 1) | array([[ 0., 3.], | [ 120., 7.], | [ 720., 11.], | [ 2184., 15.]]) | | ---------------------------------------------------------------------- | Data descriptors defined here: | | identity | The identity value. | | Data attribute containing the identity element for the ufunc, if it has one. | If it does not, the attribute value is None. | | Examples | -------- | >>> np.add.identity | 0 | >>> np.multiply.identity | 1 | >>> np.power.identity | 1 | >>> print np.exp.identity | None | | nargs | The number of arguments. | | Data attribute containing the number of arguments the ufunc takes, including | optional ones. | | Notes | ----- | Typically this value will be one more than what you might expect because all | ufuncs take the optional "out" argument. | | Examples | -------- | >>> np.add.nargs | 3 | >>> np.multiply.nargs | 3 | >>> np.power.nargs | 3 | >>> np.exp.nargs | 2 | | nin | The number of inputs. | | Data attribute containing the number of arguments the ufunc treats as input. | | Examples | -------- | >>> np.add.nin | 2 | >>> np.multiply.nin | 2 | >>> np.power.nin | 2 | >>> np.exp.nin | 1 | | nout | The number of outputs. | | Data attribute containing the number of arguments the ufunc treats as output. | | Notes | ----- | Since all ufuncs can take output arguments, this will always be (at least) 1. | | Examples | -------- | >>> np.add.nout | 1 | >>> np.multiply.nout | 1 | >>> np.power.nout | 1 | >>> np.exp.nout | 1 | | ntypes | The number of types. | | The number of numerical NumPy types - of which there are 18 total - on which | the ufunc can operate. | | See Also | -------- | numpy.ufunc.types | | Examples | -------- | >>> np.add.ntypes | 18 | >>> np.multiply.ntypes | 18 | >>> np.power.ntypes | 17 | >>> np.exp.ntypes | 7 | >>> np.remainder.ntypes | 14 | | signature | | types | Returns a list with types grouped input->output. | | Data attribute listing the data-type "Domain-Range" groupings the ufunc can | deliver. The data-types are given using the character codes. | | See Also | -------- | numpy.ufunc.ntypes | | Examples | -------- | >>> np.add.types | ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', | 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', | 'GG->G', 'OO->O'] | | >>> np.multiply.types | ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', | 'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', | 'GG->G', 'OO->O'] | | >>> np.power.types | ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', | 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G', | 'OO->O'] | | >>> np.exp.types | ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O'] | | >>> np.remainder.types | ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L', | 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O']
result = []
for i in range(10):
s = i ** 2
result.append(s)
print sum(result)
285
print sum([i**2 for i in xrange(10)])
285
# []가 없어도 되네?!
print sum(i**2 for i in xrange(10))
285