ホームページ  >  記事  >  バックエンド開発  >  Python の学習: Python に関する 17 のヒント

Python の学習: Python に関する 17 のヒント

Tomorin
Tomorinオリジナル
2018-08-23 17:47:462010ブラウズ

Python は非常に簡潔な言語です。Python の は非常に簡潔で使いやすいため、人々はこの言語の移植性を嘆かなければなりません。この記事では、非常に役立つ Python のヒント を 17 個リストします。これらの 17 のヒント は非常にシンプルですが、一般的に使用されており、さまざまなアイデアを生み出すことができます。

多くの人は、 Python 高級プログラミング言語 であることを知っています。その設計の中心的なコンセプトは、コードの可読性と、プログラマーがコードの数行を渡すことができるようにすることです。コード アイデアや創造性を簡単に表現できます。実際、多くの人が Python を学ぶことを選択する主な理由は、その プログラミング の美しさであり、それを使用して コード を作成し、表現するのは非常に自然です。アイデア。さらに、Pythonwriting はさまざまな方法で使用でき、データ サイエンス、Web 開発、機械学習はすべて 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))

リスト内で最も頻度が高い 値を検索します

#

"""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))

2 つの文字列が異なる順序で同じ文字で構成されているかどうかを確認します

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) )

チェーン比較


""" 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))

コピー リスト #

 """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)


辞書取得メソッド

""" 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))

辞書要素を「キー」で並べ替えます

"""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))

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; )

リストをカンマ区切り形式に変換します



  """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)))

辞書をマージ


##

"""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)
リストの最小値と最大値 インデックス
"""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))

リスト内の重複要素を削除する

  """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( )))
上記は、実践的で効果的な 17 個の小さな操作です。 Python プログラミング




以上がPython の学習: Python に関する 17 のヒントの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。