Python learning: 17 tips about Python

Tomorin
Release: 2018-08-23 17:47:46
Original
2060 people have browsed it

Python is a very concise language. python's is so concise and easy to use that people have to lament the portability of this language. In this article, we list 17 very useful Python tips. These 17 tips are very simple, but they are commonly used and can stimulate different ideas.

Many people know that Python is a high-level programming language. The core concept of its design is the readability of code and allowing programmers to pass several lines of code Express your ideas and creativity easily. In fact, the primary reason why many people choose to learn Python is the beauty of its programming, and it is very natural to use it to code and express ideas. In addition, Python's writing can be used in many ways. Data science, web development, and machine learning can all use Python. Quora, Pinterest, and Spotify all use Python as their backend development language.

Exchange variable values

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

Change the All elements are combined into a string
##

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

Find the value with the highest frequency in the list

"""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))
Copy after login

Check whether two strings are composed of the same letters in different orders


from collections import Counter
Counter(str1)==Counter(str2)
Copy after login

Reverse string


"""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]))
Copy after login

Reverse List


 """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 )
Copy after login

Transpose two-dimensional array

"""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) )
Copy after login

Chain comparison


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

Chain function call

"""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))
Copy after login

Copy List


 """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)
Copy after login

Dictionary get method


""" 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))
Copy after login

Sort dictionary elements by "key"


"""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))
Copy after login

For Else

##

"""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; )
Copy after login

Convert the list to comma delimited format


  """converts list to comma separated string"""
items = [foo&#39;, &#39;bar&#39;, &#39;xyz&#39;]
print (&#39;,&#39;.join( items))
"""list of numbers to comma separated"""
numbers = [2, 3, 5, 10]
print (&#39;,&#39;.join(map(str, numbers)))
"""list of mix data"""
data = [2, &#39;hello&#39;, 3, 3,4]
print (&#39;,&#39;.join(map(str, data)))
Copy after login

Merge dictionary

##

"""merge dict&#39;s"""
d1 = {&#39;a&#39;: 1}
d2 = {&#39;b&#39;: 2}
# python 3.5 
print({**d1, **d2})
print(dict(d1. items( ) | d2. items( )))
d1. update(d2)
print(d1)
Copy after login

Minimum and maximum value in the list Index

"""Find Index of Min/Max Element .
"""
lst= [40, 10, 20, 30]
def minIndex(lst): 
  return min( range(len(lst)), key=lst.. getitem__ )
def maxIndex(lst):
  return max( range( len(lst)), key=lst.. getitem__ )
print( minIndex(lst)) 
print( maxIndex(lst))
Copy after login

Remove duplicate elements in the list

  """remove duplicate items from list. note: does, not preserve the original list order"""
items=[2,2,3,3,1]
newitems2 = list(set( items)) 
print (newitems2)
"""remove dups and, keep. order"""
from collections import OrderedDict
items = ["foo", "bar", "bar", "foo"]
print( list( orderedDict.f romkeys(items ).keys( )))
Copy after login


The above is about 17 practical and effective small operations in Python programming



# #

The above is the detailed content of Python learning: 17 tips about Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!