Python突击(一)

快速过一遍Python中常用的数据类型和程序结构以及基本语法。主要有列表,字典,for循环语法,if-else语句等基本知识。

1. 列表

列表是有序集合,可以修改,用中括号[ ]修饰,下标从0开始。形如colors = ['red','blue','black','green']

访问和修改元素

colors[index]

末尾添加元素

colors.append()

插入元素

colors.insert(index, content)

删除元素

del colors[index] 等同于colors.pop(index)     区别于colors.pop()删除后能够接着使用

根据值删除元素

colors.remove(content)

排序

colors.sort()

翻转

colors.reverse()

确定长度

len(colors)

切片

colors[0:2]指的是'mouse','display'
colors[-3:]输出后面三个

遍历切片

也是for循环  for color in colors[0:3]

复制列表

new = colors[:] 不加任何索引

元组:不可变的列表,用圆括号( )修饰

形如values = (10,20,30)  values[0] = 40(ERROR)   values = (20,30,40)(Right)可以重新赋值,但不能够修改

2. 字典

字典就是键-值对,用{ }来修饰,形如student = {'name':'zs','score':'90','age':'25'}

访问字典中的value

print(student['score'])

修改字典中的值

student['score'] = '80'

添加键-值对

student['height'] = '175'

删除键-值对

del['age']

遍历所有的键值对

for key,value in student.item():

遍历所有的键

for key in student.keys():

遍历所有的值

for key in student.values():

字典列表

本质上是列表,存储的元素为字典    这里和指针数组和数组指针很像

在字典中存储列表

本质上是字典

3. 程序结构

for循环   for cat in cats:       python中通过缩进,C语言中要用{ },不要遗漏冒号

 

if 条件:

   语句1

else:

   语句2

多个条件时,用and 或者or 连接

range(1,10,2)函数

左闭右开,1~9,步长为2

digits = list(range(1,10,2))

求最大值,最小值,求和

转换成数字列表

max(),min(),sum()

**

表示平方

原文地址:https://www.cnblogs.com/wht123/p/14233530.html