>  기사  >  백엔드 개발  >  Python 학습: Python에 관한 17가지 팁

Python 학습: Python에 관한 17가지 팁

Tomorin
Tomorin원래의
2018-08-23 17:47:462009검색

Python은 매우 간결한 언어입니다. python의 은 매우 간결하고 사용하기 쉬워서 이 언어의 이식성에 감탄할 수밖에 없습니다. 이 글에서는 매우 유용한 17가지 Python 팁 을 나열합니다. 이 17가지 팁 은 매우 간단하지만 일반적으로 사용되며 다양한 아이디어에 영감을 줄 수 있습니다.

많은 사람들이 Python 고급 프로그래밍 언어라는 것을 알고 있습니다. Python 디자인의 핵심 개념은 코드의 가독성과 프로그래머가 몇 줄의 코드를 통해 아이디어와 창의성을 쉽게 표현할 수 있도록 하는 것입니다. 실제로 많은 사람들이 Python을 배우기로 선택하는 가장 큰 이유는 프로그래밍의 아름다움입니다. 이는 코딩과 아이디어 표현을 매우 자연스럽게 만들어줍니다. 또한 Python글쓰기에 사용하는 방법은 다양합니다. 데이터 과학, 웹 개발, 기계 학습 모두 Python을 사용할 수 있습니다. Quora, Pinterest 및 Spotify는 모두 백엔드 개발 언어로 Python 을 사용합니다.

변수 값 교환

"""pythonic way of value swapping"""
a, b=5,10
print(a,b)
a,b=b,a
print(a,b)

목록의 모든 요소를 ​​문자열로 결합

a=["python","is","awesome"]
print("  ".join(a))

목록 IF 찾기 가장 높은 비율의 가치

"""most frequent element in a list"""
a=[1,2,3,1,2,3,2,2,4,5,1]
print(max(set(a),key=a.count))
"""using Counter from collections"""
from collections import Counter
cnt=Counter(a)
print(cnt.most_commin(3))

두 문자열이 같은 문자로 서로 다른 순서로 구성되어 있는지 확인하세요


from collections import Counter
Counter(str1)==Counter(str2)

문자열 반전


"""reversing string with special case of slice step param"""
  a ='abcdefghij k lmnopqrs tuvwxyz 'print(a[ ::-1] )
  """iterating over string contents in reverse efficiently."""
  for char in reversed(a):
  print(char )
  """reversing an integer through type conversion and slicing ."""
  num = 123456789
  print( int( str(num)[::1]))

역순 목록


 """reversing list with special case of slice step param"""
  a=[5,4,3,2,1]
  print(a[::1])
  """iterating over list contents in reverse efficiently ."""
  for ele in reversed(a):
  print(ele )

2차원 배열 전치

"""transpose 2d array [[a,b], [c,d], [e,f]] -> [[a,c,e], [b,d,f]]"""
original = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip( *original )
print(list( transposed) )

체인 비교


rr

체인 함수 호출

""" chained comparison with all kind of operators"""
b  =6
print(4< b < 7 )
print(1 == b < 20)

목록 복사


"""calling different functions with same arguments based on condition"""
def  product(a, b):    
    return a * b
def  add(a, b):   
    return a+ b
b =True
print((product if b else add)(5, 7))

Dictionary get method


 """a fast way to make a shallow copy of a list"""
  b=a
  b[0]= 10
 """ bothaandbwillbe[10,2,3,4,5]"""
 b = a[:]b[O] = 10
  """only b will change to [10, 2, 3, 4, 5] """
  """copy list by typecasting method"""
  a=[l,2,3,4,5]
print(list(a))
  """using the list.copy( ) method ( python3 only )""" 
  a=[1,2,3,4,5]
  print(a.copy( ))
  """copy nested lists using copy. deepcopy"""
  from copy import deepcopy
  l=[l,2],[3,4]]
  l2 = deepcopy(l)
print(l2)

정렬 "key"


""" returning None or default value, when key is not in dict""" 
d = [&#39;a&#39;: 1, &#39;b&#39;: 2]
print(d.get(&#39;c&#39;, 3))

의 사전 요소 reee목록에서 가장 작은 값과 가장 큰 값의 인덱스

"""Sort a dictionary by its values with the built-in sorted( ) function and a &#39; key&#39; argument ."""
  d = {&#39;apple&#39;: 10, &#39;orange&#39;: 20, &#39; banana&#39;: 5, &#39;rotten tomato&#39;: 1)
   print( sorted(d. items( ), key=lambda x: x[1]))
  """Sort using operator . itemgetter as the sort key instead of a lambda"""
  from operator import itemgetter
  print( sorted(d. items(), key=itemgetter(1)))
  """Sort dict keys by value"""
  print( sorted(d, key=d.get))


목록에서 중복 요소 제거


"""else gets called when for loop does not reach break statement"""
a=[1,2,3,4,5]
for el in a: 
 if el==0: 
  break
else: 
 print( &#39;did not break out of for  loop&#39; )
위는 Python 프로그래밍에서 실용적이고 효과적인 약 17가지 작은 작업입니다



위 내용은 Python 학습: Python에 관한 17가지 팁의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.