Sei sulla pagina 1di 10

PYTHON TRICKS

Mohammed Shokr
PYTHON DAILY

#! /usr/bin/env python3
"""simple tuple and dictionary unpacking"""
def product(a, b):
return a * b
argument_tuple = (1, 1)
argument_dict = {'a': 1, 'b': 1}
print(product(*argument_tuple))
print(product(**argument_dict))

#! /usr/bin/env python3
""" True and False can be used as integer values [ True -> 1 , False -> 0 """
a=5
print(isinstance(a, int) + (a <= 10))
print(["is odd", "is even"][a % 2 == 0])

#!/usr/bin/env python3
"""
This program lets you create a simple command line calculator without using
the 'if..else' construct. It uses built-in 'operator' module to accomplish the
same.
"""
import operator
ops = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul
}
x = input("Enter an operator [OPTIONS: +, -, *, /]: ")
y = int(input("Enter number: "))
z = int(input("Enter number: "))
print (ops[x](y, z))

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

#! /usr/bin/env python3
"""Concatenate long strings elegantly across line breaks in code"""
my_long_text = ("We are no longer the knights who say Ni! "
"We are now the knights who say ekki-ekki-"
"ekki-p'tang-zoom-boing-z'nourrwringmm!")

#! /usr/bin/env python3
"""Python has two ways to do conditional assignments
The first is a fairly standard teranary style;
<value if true> if <conditional> else <value if false>
The second method takes advantage of the fact that python's or is lazy. When
an assignment is made if the first value is falsy (None is falsy), then it will
automatically return the second value, even if that value is falsy.
"""
b = True
print(True if b else False)
b = None or False
print(b)

#! /usr/bin/env python3
"""calling different functions with same arguments based on condition"""
def product(a, b):
return a * b
def subtract(a, b):
return a - b
b = True
print((product if b else subtract)(1, 1))

# a file when it has been read


with open('README.md') as f:
contents = f.read()
exec('code') # execute code

#! /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))

#! /usr/bin/env python3
"""a fast way to make a shallow copy of a list"""
a = [1, 2, 3, 4, 5]
print(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 = [[1, 2], [3, 4]]
l2 = deepcopy(l)
print(l2)

#! /usr/bin/env python3
"""control the whitespaces in string"""
s = 'The Little Price'
# justify string to be at least width wide
# by adding whitespaces
width = 20
s1 = s.ljust(width)
s2 = s.rjust(width)
s3 = s.center(width)
print(s1) # 'The Little Price '
print(s2) # ' The Little Price'
print(s3) # ' The Little Price '
# strip whitespaces in two sides of string
print(s3.lstrip()) # 'The Little Price '
print(s3.rstrip()) # ' The Little Price'
print(s3.strip()) # 'The Little Price'

#! /usr/bin/env python3
"""exec can be used to execute Python code during runtime
variables can be handed over as a dict
"""
exec("print('Hello ' + s)", {'s': 'World'})

#!/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)

#! /usr/bin/env python3
"""Swaps keys and values in a dict"""
_dict = {"one": 1, "two": 2}
# make sure all of dict's values are unique
assert len(_dict) == len(set(_dict.values()))
reversed_dict = {v: k for k, v in _dict.items()}

#! /usr/bin/env python3
"""
Deep flattens a nested list
Examples:
>>> list(flatten_list([1, 2, [3, 4], [5, 6, [7]]]))
[1, 2, 3, 4, 5, 6, 7]
>>> list(flatten_list(['apple', 'banana', ['orange', 'lemon']]))
['apple', 'banana', 'orange', 'lemon']
"""
# Flatten list of lists
a = [[1, 2], [3, 4]]
# Solutions:
print([x for _list in a for x in _list])
# Or
import itertools
print(list(itertools.chain(*a)))

#! /usr/bin/env python3
"""allows collecting not explicitly assigned values into a placeholder variable"""
a, *b, c = range(10)
print(a, b, c)

"""lightweight switch statement"""


#! /usr/bin/env python3
def add(a, b):
return a + b
def subtract(a, b):
return a - b
b={
'+': add,
'-': subtract
}
print(b['+'](1, 1))

#! /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)))

#! /usr/bin/env python3
"""split a string max times"""
string = "a_b_c"
print(string.split("_", 1))
"""use maxsplit with arbitrary whitespace"""
s = "foo bar foobar foo"
print(s.split(None, 2))

#! /usr/bin/env python3
dctA = {'a': 1, 'b': 2, 'c': 3}
dctB = {'b': 4, 'c': 3, 'd': 6}
"""loop over dicts that share (some) keys in Python3"""
for ky in dctA.keys() & dctB.keys():
print(ky)
"""loop over dicts that share (some) keys and values in Python3"""
for item in dctA.items() & dctB.items():
print(item)

#! /usr/bin/env python3
"""easy string formatting using dicts"""
d = {'name': 'Jeff', 'age': 24}
print("My name is %(name)s and I'm %(age)i years old." % d)
"""for .format, use this method"""
d = {'name': 'Jeff', 'age': 24}
print("My name is {name} and I'm {age} years old.".format(**d))
"""alternate .format method"""
print("My name is {} and I'm {} years old.".format('Jeff','24'))
"""dict string formatting"""
c = {'email': 'jeff@usr.com', 'phone': '919-123-4567'}
print('My name is {0[name]}, my email is {1[email]} and my phone number is
{1[phone]}'.format(d, c))

#!/usr/bin/env python3
"""nested functions"""
def addBy(val):
def func(inc):
return val + inc
return func
addFive = addBy(5)
print(addFive(4))
addThree = addBy(3)
print(addThree(7))

#! /usr/bin/env python3
""" Convert raw string integer inputs to integers """
str_input = "1 2 3 4 5 6"
print("### Input ###")
print(str_input)
int_input = map(int, str_input.split())
print("### Output ###")
print(list(int_input))

#! /usr/bin/env python3
""" Return the value of the named attribute of an object """
class obj():
attr = 1
foo = "attr"
print(getattr(obj, foo))

#! /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()))

#! /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)

#! /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]))

#! /usr/bin/env python3
"""set global variables from dict"""
d = {'a': 1, 'b': 'var2', 'c': [1, 2, 3]}
globals().update(d)
print(a, b, c)

#! /usr/bin/env python3
"""Sort a list and store previous indices of values"""
# enumerate is a great but little-known tool for writing nice code
l = [4, 2, 3, 5, 1]
print("original list: ", l)
values, indices = zip(*sorted((a, b) for (b, a) in enumerate(l)))
# now values contains the sorted list and indices contains
# the indices of the corresponding value in the original list
print("sorted list: ", values)
print("original indices: ", indices)
# note that this returns tuples, but if necessary they can
# be converted to lists using list()

#! /usr/bin/env python3
"""stepwise slicing of arrays"""
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(a[::3])

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

# -*- coding: utf-8 -*from bottle import route, run


@route('/hello')
def hello():
return u"<h1>< /h1>"
run(host='0.0.0.0', port=8080)

Potrebbero piacerti anche