Monday, December 19, 2011

Python Looping Techniques

looping thru list

li = ['cube', 'sphere', 'reactangle' ]
for i, v in enumerate(li):
    print i,v

0 cube
1 sphere
2 reactangle

Looping thru Dictionary

a = {'translate': '25', 'rotate': '4'} 
for k, v in a.iteritems():
     print k, v
translate 25
rotate 4

List Comprehension


squares = [x**2 for x in range(10)]
 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

squares = map(lambda x: x**2, range(10))
 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]




Thursday, December 15, 2011

Python: list objects to string

Python tips - How to easily convert a list to a string for display

if it is a list of strings, you may simply use join this way:

>>> mylist = ['spam', 'ham', 'eggs']
>>> print ', '.join(mylist)
spam, ham, eggs 
 
Using the same method, you might also do this:
>>> print '\n'.join(mylist) spam ham eggs
spam
ham
eggs
 
u can store the result in string variable. this time its and empty space between list objects 
 >>> c =  ' '.join(mylist)
spam ham eggs  

for non-string objects, such as integers.
If you just want to obtain a comma-separated string, you may use this shortcut:
>>> list_of_ints = [820, 547, 8080, 8081] 
>>> print str(list_of_ints).strip('[]') 
820, 547, 8080, 8081 


Or this one, if your objects contain square brackets:
>>> print str(list_of_ints)[1:-1] 
820, 547, 8080, 8081 


Finally, you may use map() to convert each item in the list to a string, and then join them:
>>> print ', '.join(map(str, list_of_ints)) 
820, 547, 8080, 8081 
>>> print '\n'.join(map(str, list_of_ints)) 
820 547 8080 8081

Integration/Tracking Demo Reel 2018 on Youtube