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

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



相关文章

python 如何快速找出两个电子表中数据的差异

最近刚接触python,找点小任务来练练手,希望自己在实践中不断的锻炼自己解决问题的能力。 公司里会有这样的场景:有一张电子表格的内容由两三个部门或者更多的部门用到,这些员工会在维护这些...

对于Python的框架中一些会话程序的管理

 Django, Bottle, Flask,等所有的python web框架都需要配置一个SECRET_KEY。文档通常推荐我们使用随机的值,但我很难发现他有任何文字说明,因...

django数据关系一对多、多对多模型、自关联的建立

一对多模型 一对多的关系,例如员工跟部门。一个部门有多个员工。那么在django怎么建立这种表关系呢? 其实就是利用外键,在多的一方,字段指定外键即可。例如员工和部门,员工是多,所以在...

spark dataframe 将一列展开,把该列所有值都变成新列的方法

spark dataframe 将一列展开,把该列所有值都变成新列的方法

The original dataframe 需求:hour代表一天的24小时,现在要将hour列展开,每一个小时都作为一个列 实现: val pivots = beijingGe...

python pyheatmap包绘制热力图

利用python pyheatmap包绘制热力图,供大家参考,具体内容如下 import matplotlib.pyplot as plt from pyheatmap.heatma...