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' #正确

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



相关文章

Python3 pip3 list 出现 DEPRECATION 警告的解决方法

需要在 ~/.pip/pip.conf 配置文件中加入下面的语句,避免这类警告: 没有目录或没有配置文件需要自己新建 mkdir ~/.pip/ cd ~/.pip touch pip....

利用Python进行异常值分析实例代码

利用Python进行异常值分析实例代码

前言 异常值是指样本中的个别值,也称为离群点,其数值明显偏离其余的观测值。常用检测方法3σ原则和箱型图。其中,3σ原则只适用服从正态分布的数据。在3σ原则下,异常值被定义为观察值和平均值...

Python实现将Excel转换成xml的方法示例

本文实例讲述了Python实现将Excel转换成xml的方法。分享给大家供大家参考,具体如下: 最近写了个小工具 用于excel转成xml 直接贴代码吧: #coding=utf-8...

Python整数对象实现原理详解

Python整数对象实现原理详解

整数对象在Python内部用PyIntObject结构体表示: typedef struct { PyObject_HEAD long ob_ival; } PyIntObject;...

python基于plotly实现画饼状图代码实例

python基于plotly实现画饼状图代码实例

这篇文章主要介绍了python基于plotly实现画饼状图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 代码 impo...