a = 5 实际a的类型由 =号右边的值定义,在Python中叫“动态类型 ”
type(a) #查看当前类型
In [1]: s = "hello"
In [2]: i = 5
In [3]: type(s)
Out[3]: str
In [4]: type(i)
Out[4]: int
l1 = [] 列表类型
d = {} 字典类型
列表的操作:
追加:l1.append("a") #如果是单独的列表,建议使用append进行追加,如果是列表的合并,可以用+=
切片:与字符串操作一样
删除:pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
l1.pop() 删除最后一个添加的
l1.pop(0)删除第一个添加的
l1.pop(-1)删除最后一个
关系:in关系 同字符串操作
s = ["a","hello"]
h in s -->False
h in s[1] -->True
比较关系:cmp()
用法: cmp(list1, list2)
方法:range(3,-1,-1)
函数原型:range(start, end, scan):
参数含义:start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5);
end:技术到end结束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
scan:每次跳跃的间距,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
小练习2:定义一个列表,实现s[::-1]的效果
方法1用range实现:
l2 = ['.cn','.com','.net']
l3 = []
for a in range(2,-1,-1):
l3 += [l2[a]]
print l3
l1 = []
l2 = ['.cn','.com','.net']
i = len(l2)
for a in range(0,i):
l1 += [l2.pop()]
print l1
方法3,用insert实现:
l1 = []
l2 = ['.cn','.com','.net']
i = len(l2)
for a in range(0,i):
l1.insert(0,[l2[a]])
print l1
插入:insert()
函数用于将指定对象插入列表。
小练习:
C逻辑:
l1 = ["a","b","c"]
l2 = ["d","e","c"]
i1 = len(l1)
i2 = len(l2)
for a in range(0,i1):
for b in range(0,i2):
if l1[a] == l2[b]:
print l1[a]
Python逻辑:
l1 = ["a","b","c"]
l2 = ["d","e","c"]
for a in l1:
if a in l2:
print(a)
小练习:公交换乘(只涉及换乘1次的)
#假设一共有100趟公交车
all = [L1,L2,L3,L4 ... L100 ]
start_station = "航天桥"
end_station = "北太平庄"
start_list = []
end_list = []
#先取出经过start_station的所有公交车(start_list)
for Road in all:
if start_station in Road:
start_list.append(Road)
#再取出经过station的所有公交车(start_list)
for Road in all:
if end_station in Road:
end_list.append(Road)
#定义一个公用的方法
def is_transfer(s,e):
for a in s:
if a in e:
print a
#调用方法
for s in start_list:
for e in end_list:
is_transfer(s,e)
extend方法
列表,字符串(可遍历的)按单个添加到尾部。append是整体添加
isinstance(数据 ,类型)