피보나치 수열
>>> fibs [0, 1]>>> n=input('How many Fibonacci numbers do your what?') How many Fibonacci numbers do your what?10 >>> for n in range(n-2): fibs.append(fibs[-2]+fibs[-1]) >>> fibs [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
참고: 내장된 호출 가능 함수를 사용하여 함수를 호출할 수 있는지 여부를 결정할 수 있습니다.
def 함수 정의
>>> def hello(name): print "Hello"+name >>> hello('world') Helloworld
함수를 사용하여 피보나치 수열 작성
>>> def fibs(num): s=[0,1] for i in range(num-2): s.append(s[-2]+s[-1]) >>> fibs(10)
참고: return 문은 함수
함수 설명 의 값을 반환합니다. 다른 사람이 이해할 수 있도록 함수를 문서화하는 경우 주석을 추가할 수 있습니다. ( #시작). 또 다른 방법은 문자열을 직접 작성하는 것입니다.
>>> def square(x): 'Calculates the square of the number x.' return x*x >>> square.__doc__ 'Calculates the square of the number x.'
내장 도움말 기능은 문서 문자열을 포함하여 함수에 대한 정보를 얻을 수 있습니다
>>> help(square) Help on function square in module __main__: square(x) Calculates the square of the number x.
함수 내의 매개변수에 새 값을 할당해도 외부 변수의 값은 변경되지 않습니다.
>>> def try_to_change(n): n='Mr,Gumby' >>> name='Mrs,Entity' >>> try_to_change(name) >>> name 'Mrs,Entity'
문자열(숫자 포함) 및 튜플) 불변입니다. 즉, 수정할 수 없습니다. 변경 가능한 데이터 구조(목록 또는 사전)가 수정되면 매개변수가 수정됩니다
>>> n=['Bob','Alen'] >>> def change(m): m[0]='Sandy' >>> change(n[:]) >>> n ['Bob', 'Alen'] >>> change(n) >>> n ['Sandy', 'Alen']
키워드 매개변수 및 기본값
>>> def hello(name,greeting='Hello',punctuation='!'): print '%s,%s%s' % (greeting,name,punctuation) >>> hello(name='Nsds') Hello,Nsds! >>> hello(name='Nsds',greeting='Hi') Hi,Nsds!
매개변수 수집
튜플 반환:
>>> def print_params(*params): print params >>> print_params('Testing') #返回元组 ('Testing',) >>> print_params(1,2,3) (1, 2, 3) >>> def print_params_2(title,*params): print title print params >>> print_params_2('Params:',1,2,3) Params: (1, 2, 3)
사전 반환
>>> def print_params_3(**params): print params >>> print_params_3(x=1,y=2,z=3) {'y': 2, 'x': 1, 'z': 3} >>> def print_params_4(x,y,z=3,*pospar,**keypar): print x,y,z print pospar print keypar >>> print_params_4(1,2,3,5,6,7,foo=1,bar=2) 2 3 (5, 6, 7) {'foo': 1, 'bar': 2} >>> print_params_4(1,2) 2 3 () {}
튜플 호출, 사전
>>> def add(x,y):return x+y >>> params=(1,2) >>> add(*params) >>> def with_stars(**kwds): print kwds['name'],'is',kwds['age'],'years old'] >>> def without_starts(kwds): print kwds['name'],'is',kwds['age'],'years old' >>> args={'name':'Nsds','age':24} >>> with_stars(**args) Nsds is 24 years old >>> without_starts(args) Nsds is 24 years old >>> add(2,args['age'])
별표는 함수를 정의(가변 개수의 매개변수 허용)하거나 호출(사전 또는 시퀀스 "분할")할 때만 유용합니다.
>>> def foo(x,y,z,m=0,n=0): print x,y,z,m,n >>> def call_foo(*args,**kwds): print "Calling foo!" foo(*args,**kwds) >>> d=(1,3,4) >>> f={'m':'Hi','n':'Hello'} >>> foo(*d,**f) 3 4 Hi Hello >>> call_foo(*d,**f) Calling foo! 3 4 Hi Hello
여러 예
>>> def story(**kwds): return 'Once upon a time,there was a' \ '%(job)s called %(name)s.' % kwds >>> def power(x,y,*others): if others: print 'Received redundant parameters:',others return pow(x,y) >>> def interval(start,stop=None,step=1): if stop is None: start,stop=0,start #start=0,stop=start result=[] i=start while i<stop: result.append(i) i+=step return result >>> print story(job='king',name='Gumby') Once upon a time,there was aking called Gumby. >>> print story(name='Sir Robin',job='brave knight') Once upon a time,there was abrave knight called Sir Robin. >>> params={'job':'language','name':'Python'} >>> print story(**params) Once upon a time,there was alanguage called Python. >>> del params['job'] >>> print story(job='store of genius',**params) Once upon a time,there was astore of genius called Python. >>> power(2,3) >>> power(y=3,x=2) >>> params=(5,)*2 >>> power(*params) >>> power(3,3,'Helld,world') Received redundant parameters: ('Helld,world',) >>> interval(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> interval(1,5) [1, 2, 3, 4] >>> power(*interval(3,7)) Received redundant parameters: (5, 6)
전역 변수 수정
>>> def f(): global x x=x+1 >>> f() >>> x >>> f() >>> x
중첩
>>> def multiplier(factor): def multiplyByFactor(number): return number*factor return multiplyByFactor >>> double=multiplier(2) >>> double(5) >>> multiplier(2*5) <function multiplyByFactor at 0x0000000002F8C6D8> >>> multiplier(2)(5)
재귀(호출)
팩토리얼 및 거듭제곱
>>> def factorial(n): if n==1: return 1 else: return n*factorial(n-1) >>> factorial(5) >>> range(3) [0, 1, 2] >>> def power(x,n): result=1 for i in range(n): result *= x return result >>> power(5,3)
>>> def power(x,n): if n==0: return 1 else: return x*power(x,n-1) >>> power(2,3)
바이너리 검색
>>> def search(s,n,min=0,max=0): if max==0: max=len(s)-1 if min==max: assert n==s[max] return max else: middle=(min+max)/2 if n>s[middle]: return search(s,n,middle+1,max) else: return search(s,n,min,middle) >>> search(seq,100)
지도 함수
함수와 목록을 받고, 이 함수를 사용하여 목록의 각 요소에 대해 차례로 작업을 수행하여 새 목록을 얻고
>>> map(str,range(10)) ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] >>> def f(x): return x*x >>> print map(f,[1,2,3,4,5,6,7]) [1, 4, 9, 16, 25, 36, 49]
>>> def format_name(s): s1=s[0].upper()+s[1:].lower() return s1 >>> print map(format_name,['ASDF','jskk']) ['Asdf', 'Jskk']
필터 기능
함수를 받아와 list(리스트)는 각 요소를 차례로 판단하여 True 또는 False를 반환하는 함수입니다. filter()는 판단 결과에 따라 조건에 맞지 않는 요소를 자동으로 필터링하고 조건에 맞는 요소로 구성된 새로운 목록을 반환합니다. 🎜>>>> def is_not_empty(s): return s and len(s.strip())>0 >>> filter(is_not_empty,[None,'dshk',' ','sd']) ['dshk', 'sd'] >>> def pfg(x): s=math.sqrt(x) if s%1==0: return x >>> import math >>> pfg(100) >>> pfg(5) >>> filter(pfg,range(100)) [1, 4, 9, 16, 25, 36, 49, 64, 81] >>> def is_sqr(x): return math.sqrt(x)%1==0 >>> is_sqr(100) True >>> filter(is_sqr,range(100)) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]람다 함수
는 익명 함수라고도 합니다. 즉, 함수에는 특정 이름이 없으며 다음과 같습니다. def로 생성된 메소드는 함수를 수신하는
>>> def foo():return 'Begin' >>> lambda:'begin' <function <lambda> at 0x0000000002ECC2E8> >>> s=lambda:'begin' >>> print s() begin >>> s= lambda x,y:x+y >>> print s(1,2) >>> def sum(x,y=6):return x+y >>> sum2=lambda x,y=6:x+y >>> sum2(4)
>>> filter(lambda x:x*x,range(1,5)) [1, 2, 3, 4]>>> map(lambda x:x*x,range(1,5)) [1, 4, 9, 16]>>> filter(lambda x:x.isalnum(),['8ui','&j','lhg',')j']) ['8ui', 'lhg']
reduce 함수
로 명명됩니다. 및 목록(list)인 경우 이 함수는 목록의 각 요소를 차례로 호출하고 결과 값으로 구성된 새 목록을 반환합니다.
>>> reduce(lambda x,y:x*y,range(1,5)) 24 >>> reduce(lambda x,y:x+y,[23,9,5,6],100) #初始值为100,依次相加列表中的值 143
파이썬의 함수에 대한 더 자세한 설명과 관련 글은 PHP 중국어 홈페이지를 주목해주세요!

다음 단계를 통해 Numpy를 사용하여 다차원 배열을 만들 수 있습니다. 1) Numpy.array () 함수를 사용하여 NP.Array ([[1,2,3], [4,5,6]]과 같은 배열을 생성하여 2D 배열을 만듭니다. 2) np.zeros (), np.ones (), np.random.random () 및 기타 함수를 사용하여 특정 값으로 채워진 배열을 만듭니다. 3) 서브 어레이의 길이가 일관되고 오류를 피하기 위해 배열의 모양과 크기 특성을 이해하십시오. 4) NP.Reshape () 함수를 사용하여 배열의 모양을 변경하십시오. 5) 코드가 명확하고 효율적인지 확인하기 위해 메모리 사용에주의를 기울이십시오.

BroadcastingInnumpyIsamethodtoperformoperationsonArraysoffferentShapesByAutomicallyAligningThem.itsimplifiesCode, enourseadability, andboostsperformance.here'showitworks : 1) smalraysarepaddedwithonestomatchdimenseare

forpythondatastorage, chooselistsforflexibilitywithmixeddatatypes, array.arrayformemory-effic homogeneousnumericaldata, andnumpyarraysforadvancednumericalcomputing.listsareversatilebutlessefficipforlargenumericaldatasets.arrayoffersamiddlegro

pythonlistsarebetterthanarraysformanagingDiversEdatatypes.1) 1) listscanholdementsofdifferentTypes, 2) thearedynamic, weantEasyAdditionSandremovals, 3) wefferintufiveOperationsLikEslicing, but 4) butiendess-effectorlowerggatesets.

toaccesselementsInapyThonArray : my_array [2] AccessHetHirdElement, returning3.pythonuseszero 기반 인덱싱 .1) 사용 positiveAndnegativeIndexing : my_list [0] forthefirstelement, my_list [-1] forstelast.2) audeeliciforarange : my_list

기사는 구문 모호성으로 인해 파이썬에서 튜플 이해의 불가능성에 대해 논의합니다. 튜플을 효율적으로 생성하기 위해 튜플 ()을 사용하는 것과 같은 대안이 제안됩니다. (159 자)

이 기사는 파이썬의 모듈과 패키지, 차이점 및 사용법을 설명합니다. 모듈은 단일 파일이고 패키지는 __init__.py 파일이있는 디렉토리이며 관련 모듈을 계층 적으로 구성합니다.

기사는 Python의 Docstrings, 사용법 및 혜택에 대해 설명합니다. 주요 이슈 : 코드 문서 및 접근성에 대한 문서의 중요성.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

WebStorm Mac 버전
유용한 JavaScript 개발 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구
