import os # from a directory get each file name as key and file size as value print {filename: os.path.getsize(filename) for filename in os.listdir(os.getcwd()) } # initialize from 0-9 key as true print {n: True for n in range(10)}
Friday, December 20, 2013
python dictionary comprehensions
Python dictionary comprehensions is similar to list comprehension. Lets have some example
Posted by
Abu Zahed Jony
at
5:58 PM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels:
dictionary,
pythonic
Python list comprehensions
Python list comprehensions provide many way to create list.
The comrehensions format is [*transform* *iteration* *filter* ].
Let's have some example.
The comrehensions format is [*transform* *iteration* *filter* ].
Let's have some example.
# read a file line by line check whether or not "word" contains in each line (ignore case) print [ line.strip("\n").lower() for line in open("a.in") if "word" in line] # initialize array by square number print [i**2 for i in range(10)] # initialize array with tuples print [(i,i**2) for i in range(10)] # initialize array by odd number print [i for i in range(10) if i%2] words = ["Life", "is", "very", "easy", "Python"] # print first character of each word print [word[0] for word in words] # make all words to upper case print [word.upper() for word in words] # Sum each element of two array a = [1, 2, 3] b = [4, 5, 6] print [a[i]+b[i] for i in range(len(a))]
Posted by
Abu Zahed Jony
at
5:35 PM
1 comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels:
for loop,
List,
list comprehensions,
pythonic
Thursday, December 12, 2013
Context manager API
A context manager is enabled by the with statement, and the API involves two methods. The __enter__() method is run when execution flow enters the code block inside the with. It returns an object to be used within the context. When execution flow leaves the with block, the __exit__() method of the context manager is called to clean up any resources being used.
Output:
class Context(object): def __init__(self): print "Initialize" def __enter__(self): print "Enter" def __exit__(self, exc_type, exc_val, exc_tb): print "Exit" with Context(): print "Doing something"
Output:
Initialize Enter Doing something Exit
Posted by
Abu Zahed Jony
at
10:29 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels:
Context manager,
with
Context manager API
Python file object support the context manager API to make it easy to ensure they are closed after all reading or writing is done
Output:
with open('z.txt', 'r') as f: data = f.read() print data
Output:
File content
Posted by
Abu Zahed Jony
at
10:21 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels:
Context manager,
with
Python enumerate
enumerate returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence.
Output:
a = ["Python","easy"] for i, n in enumerate(a): print i, n
Output:
0 Python 1 easy
Posted by
Abu Zahed Jony
at
9:37 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Python case insensitive dictionary
class CaseInsensitiveDict(dict): def __setitem__(self, key, value): key = key.lower() dict.__setitem__(self, key, value) def __getitem__(self, key): key = key.lower() return dict.__getitem__(self, key) d = CaseInsensitiveDict() d["Python"] = "Easy" print d["PYTHON"] print d["python"]
Output:
Easy Easy
Posted by
Abu Zahed Jony
at
9:12 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels:
Code snippet,
dictionary
Monday, December 9, 2013
Python for loop with else clauses
a = [1, 3, 51, 7, 8] print a k = 5 for n in a: if n%k==0: print "Divisible by",k,"found" break else: # This line will working if for loop terminate normally print "Divisible by",k,"not found" print a = [1, 3, 5, 7, 8] print a k = 5 for n in a: if n%k==0: print "Divisible by",k,"found" break else: # This line will working if for loop terminate normally print "Divisible by",k,"not found"
Output:
[1, 3, 51, 7, 8] Divisible by 5 not found [1, 3, 5, 7, 8] Divisible by 5 found
Posted by
Abu Zahed Jony
at
10:44 AM
0
comments
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Subscribe to:
Posts (Atom)