Important
code Snippets
==============Data
and Time: ==============
import datetime
print (datetime.datetime.now().day) # Result : 11
==============sorting reverse in list==============
liste=[1,5,9,2,3]
liste.sort(key=None, reverse=False)
import datetime
print (datetime.datetime.now().day) # Result : 11
==============sorting reverse in list==============
liste=[1,5,9,2,3]
liste.sort(key=None, reverse=False)
Method2
Print(liste[::-1]
==============remove duplicates in list==============
l=[1,5,5,9,"a","b"]
liste=list(set(l))
==============Regex==============
==============remove duplicates in list==============
l=[1,5,5,9,"a","b"]
liste=list(set(l))
==============Regex==============
import re
if(re.search(“.*ant.*”,”antelope”)): #search
print(True)
print(re.sub(r”expr”,string)) #replace
print(len(re.findall(“expr”,string)) #count
==============locals()==============
def test():
a = 1
b = 2
c= 3
return locals()
s=test()
print(s) #o/p: (a,1) ,(b,2),(c,3),
print (type(s)) # result : dict
==============Ranged if Condition==============
r=300
if (r in range(200,210,1)):
print (True)
else:
print(False)
def test():
a = 1
b = 2
c= 3
return locals()
s=test()
print(s) #o/p: (a,1) ,(b,2),(c,3),
print (type(s)) # result : dict
==============Ranged if Condition==============
r=300
if (r in range(200,210,1)):
print (True)
else:
print(False)
or
if(200<r<210):
==============Validate type ==============
if isinstance(d,dict):print("hi")
if(type(d)==dict) :print(“True”)
====Higher order functions (function name as) ====
def a():
print("hi")
def b(func):
func()
b(a) # result :hi
====Higher order class (function name as) ====
class deco :
def func1(self):
print ("funct1")
def func2(self,var):
print(var)
def some_func(obj):
obj(deco)
def some_func2(obj,var):
obj(deco,var)
some_func(deco.func1) #O/p funct1
some_func2(deco.func2,"33") #O/p: 33
==============Validate type ==============
if isinstance(d,dict):print("hi")
if(type(d)==dict) :print(“True”)
====Higher order functions (function name as) ====
def a():
print("hi")
def b(func):
func()
b(a) # result :hi
====Higher order class (function name as) ====
class deco :
def func1(self):
print ("funct1")
def func2(self,var):
print(var)
def some_func(obj):
obj(deco)
def some_func2(obj,var):
obj(deco,var)
some_func(deco.func1) #O/p funct1
some_func2(deco.func2,"33") #O/p: 33
==============Keyword
Arguments in a Function==============
def a(a=5,b): #wrong - non keyword args follow keyword ie., b should come before a
print(a,b)
def a(b,a=5): #Correct
print(a,b)
a(b=3,a=1) #Result - 31
a(1,2) #Result - 12
a(a=4,4) #Error - non Keyword argument should come before keyword argument
=========List and tuple Arbitrary Argument in Function==============
def a(*a):
for i in a:
print(i)
a([1,2,3])
a((1,2,3))
Result:
[1,2,3]
(1,2,3)
def a(a=5,b): #wrong - non keyword args follow keyword ie., b should come before a
print(a,b)
def a(b,a=5): #Correct
print(a,b)
a(b=3,a=1) #Result - 31
a(1,2) #Result - 12
a(a=4,4) #Error - non Keyword argument should come before keyword argument
=========List and tuple Arbitrary Argument in Function==============
def a(*a):
for i in a:
print(i)
a([1,2,3])
a((1,2,3))
Result:
[1,2,3]
(1,2,3)
==============Create
sequential lists in 1 line==============
x=list(range(51,60,2)) #[51, 53, 55, 57, 59]
x=list(range(51,60,2)) #[51, 53, 55, 57, 59]
==============Slicing
techniques==============
a=list(range(1,5))
#[1,2,3,4]
print(a[::-1]) #[4,3,2,1] -reverse
print(a[::2]) #[1,3]
print(a[::-2]) #[3,1]
print(a[1:-1:1]) #[2,3]
print(a[1:-1:-1]) #[]
print(a[-1:1:-1)] #[4,3]
==============List
into sublist or 1D to 2D==============
a=list(range(1,5))
#[1,2,3,4]
res=[a[i:i+2]
for i in range(0,len(a),2)]
#[[1,2][3,4]]
method2
m=[[i for i in range(j,j+3)] for j in range(1,7,3)]
#m = [[1, 2, 3], [4, 5, 6]]
===========Transpose a matrix using list comprehensions==============
n=[[m[i][j] for i in range(0,len(m))] for j in range(0,len(m[0]))]
method2
m=[[i for i in range(j,j+3)] for j in range(1,7,3)]
#m = [[1, 2, 3], [4, 5, 6]]
===========Transpose a matrix using list comprehensions==============
n=[[m[i][j] for i in range(0,len(m))] for j in range(0,len(m[0]))]
Zip Matrix
Transpose
n=list(zip(*m)) #list(zip(m[0],m[1])
Zip
Combine 2 lists
a=[1,2,3]
b=[4,5,6]
print(list(zip(a,b)))
Combine
sublists in 1 List
m
= [[1, 2, 3], [4, 5, 6]]
l=m[0]+m[1] #l=[1,2,3,4,5,6]
List
values into string
method 1 :List into string in 1 line
l = [1,2,3,7]
print ("".join([str(x) for x in l] )
method 2:
l = [1,2,3,7]
for i in l:
data=data+i
print(data)
==============Type Conversions==============
s="deepak"
s=set(list(tuple(s)))
method 1 :List into string in 1 line
l = [1,2,3,7]
print ("".join([str(x) for x in l] )
method 2:
l = [1,2,3,7]
for i in l:
data=data+i
print(data)
==============Type Conversions==============
s="deepak"
s=set(list(tuple(s)))
==============Dictionary
(Format similar to JSON)
d={'a':'1','b':1}
#dictionary creation
print(d.keys() , d.values() ) #['a', 'b'][2,3]),
print( 'a' in d) #True (list,set,tuple,str)
print(d.items()) #'a':'1','b':1
d[“key”]=””value” #access individual val
==============Add
2 Dictionaries==============
Res={**d1,**d2}
==============Exchange
2 variables==============
a,b=b,a
Count occurrences
in a list in 1 line using re
import
re
l=[1,1,2,4,4,4]
s=set(l)
res=[
len(re.findall(str(i),str(l))) for i in
s] # [2,
1, 3]
==============Fibnocci
-0,1,1,2,3,5,8…==============
res=[0,1]
for
i in range(0,5,1):
res=res+[res[-2]+res[-1]]
print(res)
==============Unit
test==============
1.”test” suffixed for unittest class.
2. import unittest and class under test
3. To run untitestuse:
D:\>C:\Python34\python.exe
-m unittest testfile.area_test.circle_area_test
import
unittest
class
area():
def circle_area(self,r):
return(3.14*r**2)
class
area_test(unittest.TestCase):
def circle_area_test(self):
a=area()
self.assertAlmostEqual(a.circle_area(0),1)
self.assertAlmostEqual(a.circle_area(0),0)
self.assertRaises(valueError,a.circle_area(0),0)
Thank you for sharing the useful information.
ReplyDeletePYTHON Training in Chennai