Tuesday, March 20, 2012

Python list comprehensions for string sub listing

I am still learning python language which apparently needed for implement some tools regarding my research. And i came through this amazing feature in python lists.
Although i know python can do amazing stuff that no other popular languages can do, this thing suprised me a lot.

So what is this list comprehensions ?
A list comprehension is a way to describe a list. If you have taken mathematics basic class you might be familiar with set theories and for each of set we use we have a definition for that set.

For an example lets say a list that has all the even numbers. We can write this definition in mathematical way like below.

E = { x | x%2=0}
This means set s has all the x values that suppress the condition of "remaining of x by 2 is 0".

When it comes to set of strings, we can define those sets in the same way.

Alphabet = { x | x in 'a' to 'z'} 
V = { a , e , i , o , u }

So in python language it has been facilitated to use the similar notation we used in mathematical definitions.

Say we want to obtain a separate list of items from a main list that has a special string within it.

prefix = "http"
dirListing = os.listdir(sys.argv[1])
httpList = [x for x in dirListing if prefix in x]

Above python sample code demonstrate how to sub list the set of strings that contains "http" within the strings from set of strings.
Here we say that "httpList" list should contain all the x values where x is in "dirListing" list and x contains "dnsString" within it.





No comments:

Post a Comment