Scroll to top

PYTHON PÜF NOKTALARI

Nadir olan ve çok kullanışlı olan python ipuçları..

DEĞIŞIM DEĞERLERI

#! /usr/bin/env python3
"""pythonic way of calue swapping"""
a, b = 5,10
print(a, b)
a, b = b, a
print(a, b

LISTEDEKI TÜM ÖĞELERDEN TEK BIR DIZE OLUŞTURUN

#! /usr/bin/env python3
a = ["Python", "is", "awesome"]
print(" ".join(a))

LISTEDE EN SIK DEĞERI BUL

#! /usr/bin/env python3
""" most frequent element in a list"""
a = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(a), key = a.count))

İKI KELIMENIN ANAGRAM OLUP OLMADIĞINI KONTROL ETME

#! /usr/bin/env python3
from collections import Counter
Counter(str1) == Counter(str2)

BIR DIZEYI TERS ÇEVIR

#! /usr/bin/env python3
"""reversing string with special case of slice step param"""
a = 'abcdefghijklmnopqrstuvwxyz'
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]))

LISTEYI TERSINE ÇEVIR

#! /usr/bin/env python3
"""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)

TRANSPOSE 2D DIZISI

#! /usr/bin/env python3
"""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))

ZINCIRLI KARŞILAŞTIRMA

#! /usr/bin/env python3
"""chained comparison with all kind of operators"""
a = 10
print(1 < a < 50)
print(10 == a < 20)

ZINCIRLI IŞLEV ÇAĞRISI

#! /usr/bin/env python3
"""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))

LISTEYI KOPYALA

#! /usr/bin/env python3
import sys
"""a fast way to make a shallow copy of a list"""
a = [1, 2, 3, 4, 5]
print(a[:])
"""adding an empty list yields a copy of initial list"""
a = [1, 2, 3, 4, 5]
print(a + [])  # in python3, for small lists performs faster than a[:]
"""copy list by typecasting method"""
a = [1, 2, 3, 4, 5]
print(list(a))
"""using the list.copy() method (python3 only)"""
if sys.version_info.major == 3:
    a = [1, 2, 3, 4, 5]
    print(a.copy())
else:
    # in python2 there exists the `copy` builtin module
    from copy import copy
    a = [1, 2, 3, 4, 5]
    print(copy(a))
"""copy nested lists using copy.deepcopy"""
from copy import deepcopy
l = [[1, 2], [3, 4]]
l2 = deepcopy(l)
print(l2)

SÖZLÜKTEN ALIN

#! /usr/bin/env python3
"""returning None or default value, when key is not in dict"""
d = {'a': 1, 'b': 2}
print(d.get('c', 3))

SÖZCÜĞÜ DEĞERE GÖRE SIRALA

#!/usr/bin/env python3
""" Sort a dictionary by its values with the built-in sorted() function and a 'key' argument. """
 
d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 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

#! /usr/bin/env python3
"""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('did not break out of for loop')

LISTEYI VIRGÜLLE AYRILMIŞ HALE GETIRIN

#! /usr/bin/env python3
"""converts list to comma separated string"""
items = ['foo', 'bar', 'xyz']
print (','.join(items))
"""list of numbers to comma separated"""
numbers = [2, 3, 5, 10]
print (','.join(map(str, numbers)))
"""list of mix  data"""
data = [2, 'hello', 3, 3.4]
print (','.join(map(str, data)))

SÖZLÜKLERI BIRLEŞTIRME

#! /usr/bin/env python3
"""merge dict's"""
d1 = {'a': 1}
d2 = {'b': 2}
# python 3.5
print ({**d1, **d2})
print(dict(d1.items() | d2.items()))
d1.update(d2)
print(d1)

LISTEDEKI MIN VE MAKS INDEKSI

#! /usr/bin/env python3
"""
Find Index of Min/Max Element.
"""
lst = [40, 10, 20, 30]
def minIndex(lst):
    return min(range(len(lst)), key=lst.__getitem__)  # use xrange if < 2.7
def maxIndex(lst):
    return max(range(len(lst)), key=lst.__getitem__)  # use xrange if < 2.7
print(minIndex(lst))
print(maxIndex(lst))

BIR LISTEDEN KOPYALARI KALDIR

#! /usr/bin/env python3
"""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.fromkeys(items).keys()))

DAHA FAZLA

Daha fazlasını burdan bulabilirsiniz PyTricks github sayfa Bu güzel ekran görüntülerini nasıl oluşturacağınızı bilmek ister misiniz? Burdan okuya bilirsiniz.

Author avatar
Novonto
https://novonto.com
As a strategic partner we craft digital-first brand programs, interactive experiences, and eCommerce flagships that differentiate and resonate in today’s consumer-centric, ever changing business environment.

Post a comment

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir