Is something empty?
it is recommended to use
other than
if len(items) != 0:
do some thing
if items != None:
do some thing |
Don’t forget ‘:’ at the end
Python uses ‘:’ to indicate a block of code. Although I think it is not necessarily need, but it is.
if some_condition:
do something
while some_condition:
do something |
use ‘pass’ if nothing to do
if some_condition:
pass
else:
do something |
NULL/true/false
Use ‘None/True/False’ instead.
logic
‘&& || !’ -> ‘and, or, not’
if not some_condition:
pass
if some_condition and another_condtion:
pass |
Indention
Indention in python is essential and compulsive. Code-block is defined by indention like {} in C++
if some_condition:
do something
do another thing # OK, indention is consist with the previous statement
else:
do something else
do another thing # Fails because indention is illegal |
Be careful to use tab and space. It is wisely to config your editor to display white-chars.
for_each
for item in item_list:
print item |
enumerate items in a container
for (index, item) in enumerate(items):
print index, item
for (key,value) in mydict.items():
print key,value |
string
‘this is a string’
“this is also a string”
”’this is a
multi-line string”’
join string
colors = ['red', 'blue', 'green', 'yellow']
result = '|'.join(colors)
print result #It will print 'red|blue|green|yellow' |
Swap
list,set,tuple,dict
list -> array/vector: ['this','is','a','list']
set -> std::set
tuple -> const list: (‘this’,'is’,'a’,'list’)
dict -> hash map: {“key1″:”value1″, “key2″:”value2″}
list to set: aNewSet = set(mylist), with duplicated item automatically removed
set to list: aNewList = list(myset)
list to tuple: aNewTuple = tuple(mylist)
tuple to list: aNewList = list(mytuple)
List comprehension
result = [x for x in xrange(10) if I % 2 == 0]
print result #will be 2 4 6 8
True?1:2
a = 1 if some_condition else 2
Reference or Value
every object is a reference to memory. python will collect an object if there is nobody refer to it.
you can use copy to clone a object
import copy
#simple copy, like in C++, do simple copy only if there is no pointer member
aNewList = copy.copy(theOldList)
#like in C++, you should do deep copy if there any pointer member
aNewList = copy.deepcopy(theOldList) |