1 键盘输入
python提供了内置的函数获得键盘的输入。这个函数是raw_input,它被调用时,程序暂停执行,等待用户输入信息。
当回车被按下后,程序继续执行。并且返回用户输入的信息。
>>> input = raw_input()
I love Python!
>>> print input
I love Python!
>>>
可以给一些提示作为用户的提醒,具体一看程序你马上就明白了~
>>> name = raw_input("Please input your name:")
Please input your name:James Guo
>>> print name
James Guo
>>>
2 继续上次笔记谈到的 关键字 “in”
not 和 in 组合在一起可以干什么?
>>> name = ["James","Lucy","Tom","Lily"]
>>> 'Mike' not in name
True
>>>
3 列表是可以变的
和字符串是不一一样子的,列表的元素是可以改变的。这是个很好的特性,可以修改,添加,删除列表的元素值。
>>> fruit = ["banana", "apple", "peach"]
>>> fruit
['banana', 'apple', 'peach']
>>> fruit[0] = "orange"
>>> fruit[-1] = "pear"
>>> fruit
['orange', 'apple', 'pear']
>>>
通过赋值,删除一些元素
>>> list = [1,2,3,4,5,6,7]
>>> id(list)
45190360
>>> list[1:3] = []
>>> print list
[1, 4, 5, 6, 7]
>>> id(list)
45190360
>>>
del 删除列表的元素
>>> a = ["one","two","three"]
>>> del a[1]
>>> a
['one', 'three']
>>>
4 变量
当你看到下面的程序你会有什么想法呢?
列表和字符串有区别吗?
>>> a = "what the hell "
>>> b = "what the hell "
>>> id(a)
45634528
>>> id(b)
45613968
>>> a = "xyz"
>>> b = "xyz"
>>> id(a)
45700760
>>> id(b)
45700760
>>> a = ["x","y","z"]
>>> b = ["x","y","z"]
>>> id(a)
44496816
>>> id(b)
44544368
>>>
5 克隆列表
如果要修改列表,但是要保留原来列表的一份拷贝,就需要列表自我复
制,这过程叫做克隆。克隆的结果是产生两个值一样,但却有不同标识符
的列表。克隆的方法是利用列表的片断操作符:
>>> x = [1,2,3,4,5,6,7]
>>> y = x[:]
>>> print y
[1, 2, 3, 4, 5, 6, 7]
>>> id(x)
4792152
>>> id(y)
45161128
>>>
修改一下呢
>>> x = [1,2,3,4,5,6,7]
>>> y = x[:]
>>> print y
[1, 2, 3, 4, 5, 6, 7]
>>> id(x)
4792152
>>> id(y)
45161128
>>> y[0] = 9
>>> print y
[9, 2, 3, 4, 5, 6, 7]
>>> print x
[1, 2, 3, 4, 5, 6, 7]
>>>
6 列表的嵌套
嵌套的列表是作为另一个列表中的元素。下面列表中的第三个元素是
一个列表。
>>> list = ["hello",314,5,[10,20,30]]
>>> elt = list[3]
>>> print elt
[10, 20, 30]
>>> elt[0]
10
>>>
7 嵌套列表可以代表矩阵
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix[1]
[4, 5, 6]
>>> matrix[1][1]
5
>>>
8 字符串和列表
>>> import string
>>> song = "The rain in Spain..."
>>> string.split(song)
['The', 'rain', 'in', 'Spain...']
>>>
split函数的另外一个参数是规定作为分隔符的字符串。分隔符不显示在列表中。
>>> string.split(song,'ai')
['The r', 'n in Sp', 'n...']
>>>
函数jion的功能和split正好相反,它是将列表连接成字符串。默认的分隔符是空格。
>>> list = ['The','rain','in','Spain...']
>>> string.join(song)
'T h e r a i n i n S p a i n . . .'
>>>
8 列表映射
>>> fruit = ['apple','orange','pear','banana']
>>> i = 0
>>> for var in fruit:
fruit[i] = var + 's'
i= i + 1
>>> print fruit
['apples', 'oranges', 'pears', 'bananas']
>>> fruit
['apples', 'oranges', 'pears', 'bananas']
>>> fruit = ['apple','orange','pear','banana']
>>> [fruit + 's' for fruit in fruit]
['apples', 'oranges', 'pears', 'bananas']
>>>
当for语句每次循环时,把一个元素赋值给变量fruit,然后这个变量再和字符‘s ’相加,最后把列表fruit的值全部更新。
上述列表映射对所有元素做了相同的的操作,如果我们只想对满足条件的元素进行处理该怎么办呢?很简单,只要在加上if 语句就行了。假如不想对字符个数等于六的元素加‘s ’,那么可用下列方法过滤列表
>>> fruit = ['apple','orange','pear','banana']
>>> [fruit + 's' for fruit in fruit if len(fruit)!= 6]
['apples', 'pears']
>>>