In [1]:
# create a list
a = range(1,10)
print a
b = ["a","b","c","d"]
print b
In [2]:
# access element by index
print a[0]
print b[-3]
In [3]:
# list can split
print a[1:6]
print a[1:]
print a[:5]
print a[-1:]
print a[:-1]
print b[1:3]
In [4]:
# list + operator
a = [1,4]
b = [5,6]
print a+b
In [5]:
# the min and max of list
print max(a)
print min(a)
In [6]:
# in and not in
if 2 in a:
print 'the element 2 is in a'
else:
print 'the element 2 is not in a'
In [7]:
# append and extend
a = range(10)
print a
a.append(10)
In [8]:
print a
In [9]:
# stack
a_stack = []
a_stack.append(1)
a_stack.append('Roc')
a_stack.append("hello")
print a_stack
In [10]:
print a_stack.pop()
print a_stack.pop()
print a_stack.pop()
In [11]:
# queue
a_queue = []
a_queue.append("who")
a_queue.append("are")
a_queue.append("you")
print a_queue
In [12]:
print a_queue.pop(0)
print a_queue.pop(0)
print a_queue.pop(0)
In [13]:
# shuffle , sort and reverse
from random import shuffle
a = range(15)
shuffle(a)
print a
In [14]:
a.sort()
print a
In [15]:
a.reverse()
print a
In [18]:
# generate list from a list
a = [1,3,5,0,-5,7,-8]
b = [pow(x,2) for x in a if x<0]
print b
In [19]:
# generate dict from dict
a = {'a':1,'b':4,'c':5}
b = {x:pow(y,2) for x,y in a.items()}
print b
In [21]:
# tuple
def process(x):
if isinstance(x,str):
return x.lower()
elif isinstance(x,int):
return x*x
else:
return -1
a = (1,2,-1,-2,'D','R',3,4,-3,'E')
b = tuple(process(x) for x in a)
print b
In [2]:
# sort 和sorted不同
from random import shuffle
a = range(10)
shuffle(a)
print a
In [3]:
# sort
a.sort()
print a
In [4]:
b = range(10)
shuffle(b)
print b
In [5]:
print sorted(b)
In [6]:
print b