python笔记(2)

yipeiwu_com6年前Python基础
继续List:

删除元素:
复制代码 代码如下:

a =[1, 2, 3, 4]
a[2:3] = [] #[1, 2, 4]
del a[2] #[1, 2]

清空list
复制代码 代码如下:

a[ : ] = []
del a[:]

list作为栈使用(后入先出):
复制代码 代码如下:

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack.pop() # 7
stack.pop() # 6
stack.pop() # 5

用负数索引:
复制代码 代码如下:

b=[1, 2, 3, 4]
b[-2] #3

"+"组合list:
复制代码 代码如下:

end = ['st', 'nd'] + 5*['th'] + ['xy'] # ['st', 'nd', 'th', 'th', 'th', 'th', 'th', 'xy']

查出某元素在list中的数量:
复制代码 代码如下:

lst.('hello') # hello 的数量

list排序:
复制代码 代码如下:

sort()
#对链表中的元素进行适当的排序。

reverse()
#倒排链表中的元素

函数指针的问题:
复制代码 代码如下:

def f2(a, L=[])
L.append(a)
return L

print(f2(1)) # 1
print(f2(2)) # 1, 2 L在这次函数调用时是[1]
print(f2(3)) # 1, 2, 3

函数中的参数中有:

  *参数名 :表示任意个数的参数

  **  :表示dictionary参数
控制语句:

 IF:
复制代码 代码如下:

if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'

FOR:
复制代码 代码如下:

a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)  

WHILE:
复制代码 代码如下:

a, b = 0, 1
while b < 1000:
print b,
a, b = b, a+b
#1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

pass :空操作语句
复制代码 代码如下:

while True:
pass

dictionary: 键值对的数据结构

用list来构造dictionary:
复制代码 代码如下:

items = [('name', 'dc'), ('age', 78)]
d = dict(items) #{'age': 78, 'name': 'dc'}

有趣的比较:
复制代码 代码如下:

x = [] #list
x[2] = 'foo' #出错
x = {} #dictionary
x[2] = 'foo' #正确

内容比较杂,学到什么就记下来。完全利用工作中的空闲和业余时间来完成,更加充实了。



相关文章

基于Django URL传参 FORM表单传数据 get post的用法实例

POST和GET是web开发中常用的表单交互方法,是构建web前后端交互系统的顶梁柱,现将Django中的简单用法示例记录下来,以供后续查询和其他同学参考 1.URL传参 #前端ht...

python学习手册中的python多态示例代码

在处理多态对象时,只需要关注它的接口即可,python中并不需要显示的编写(像Java一样)接口,在使用对象的使用先假定有该接口,如果实际并不包含,在运行中报错。复制代码 代码如下:cl...

代码分析Python地图坐标转换

最近做项目正好需要坐标的转换 各地图API坐标系统比较与转换; WGS84坐标系:即地球坐标系,国际上通用的坐标系。设备一般包含GPS芯片或者北斗芯片获取的经纬度为WGS84地...

Python判断以什么结尾以什么开头的实例

如下所示: str='abcdef' print(str.endswith('f')) print(str.startswith('a')) 输出结果: True True...

Python django使用多进程连接mysql错误的解决方法

Python django使用多进程连接mysql错误的解决方法

问题 mysql 查询出现错误 error: (2014, "Commands out of sync; you can't run this command now")1 查询 m...