list


In [1]:
# create a list
a = range(1,10)
print a
b = ["a","b","c","d"]
print b


[1, 2, 3, 4, 5, 6, 7, 8, 9]
['a', 'b', 'c', 'd']

In [2]:
# access element by index
print a[0]
print b[-3]


1
b

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]


[2, 3, 4, 5, 6]
[2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5]
[9]
[1, 2, 3, 4, 5, 6, 7, 8]
['b', 'c']

In [4]:
# list + operator
a = [1,4]
b = [5,6]
print a+b


[1, 4, 5, 6]

In [5]:
# the min and max of list
print max(a)
print min(a)


4
1

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'


the element 2 is not in a

In [7]:
# append and extend
a = range(10)
print a 
a.append(10)


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [8]:
print a


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [9]:
# stack
a_stack = []
a_stack.append(1)
a_stack.append('Roc')
a_stack.append("hello")

print a_stack


[1, 'Roc', 'hello']

In [10]:
print a_stack.pop()
print a_stack.pop()
print a_stack.pop()


hello
Roc
1

In [11]:
# queue
a_queue = []
a_queue.append("who")
a_queue.append("are")
a_queue.append("you")
print a_queue


['who', 'are', 'you']

In [12]:
print a_queue.pop(0)
print a_queue.pop(0)
print a_queue.pop(0)


who
are
you

In [13]:
# shuffle , sort and reverse
from random import shuffle
a = range(15)
shuffle(a)
print a


[2, 3, 12, 7, 6, 9, 4, 10, 13, 1, 14, 11, 5, 8, 0]

In [14]:
a.sort()
print a


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

In [15]:
a.reverse()
print a


[14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

从一个列表创建一个列表


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


[25, 64]

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


{'a': 1, 'c': 25, 'b': 16}

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


(1, 4, 1, 4, 'd', 'r', 9, 16, 9, 'e')

列表排序


In [2]:
# sort 和sorted不同
from random import shuffle
a = range(10)
shuffle(a)
print a


[0, 6, 4, 3, 2, 5, 8, 9, 1, 7]

In [3]:
# sort
a.sort()
print a


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [4]:
b = range(10)
shuffle(b)
print b


[5, 0, 2, 7, 9, 6, 4, 8, 1, 3]

In [5]:
print sorted(b)


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [6]:
print b


[5, 0, 2, 7, 9, 6, 4, 8, 1, 3]