基本数据结构
Python 的基本数据结构有以下四种:List
Tuple
Set
Dictionary
List:
List是有序的,可以修改的。
#创建列表
alist = [1,2,3,'a',(1,2,3)]
#将其他结构转为列表,若a为Tuple
list(a) #将Tuple转为列表
#list的查询
alist [0] #返回结果为1
#list切片
alist [0:2] #返回结果为[1,2]
Tuple:
Tuple是无序及不能修改的。Tuple的查询跟切片跟List一样
#创建Tuple使用()
atuple= (1,2,3,1.0,'a')
#若创建长度为1的Tuple
len_one_tuple = (1,) #而非(1), (1)的类型是int
Set:
Set是无序及不能重复的但可以修改;另外Set没有Index,所以不能跟列出一样切片。
#创建集
aset = set([1,1,2,3,4])#也可以使用{1,1,2,3,4}
#返回结果是1,2,3,4
#新增数据于设置内
aset.add(5)
aset.update(set([5,6,7,8,9])
#删除组内特定的数据
aset.remove(2)#于aset内删除2
#也可以使用
aset.discard(2)
Dict:
Dict为dictionary的简写,可储存keys及values,keys是不能重复的,另外keys只可为不可修改的数据类型或结构,e.g.:strings, tuple........
数据类型
Python的数据类型包括:string
numberinteger
float
complex
long
数据类型都是不可修改的,并可以使用list,tuple......作为容器装载。
判断语句:if 语句
#if 语句
if (condition 1):
statement 1......
elif (condition 2):
statement 2......
elif (condition 3):
statement 3......
else:
statement 4......
如果符合条件1,即运行语句1的代码,如符合条件2,即运行语句2的代码,如皆不符合if和elif的情况,将会运行else的代码。
循环语句for 循环
while 循环
for循环适合可迭代器,如list,tuple;
while循环适合已设定循环条件下使用,如: a<10时循环等
break 用于结束整个循环
continuous 不执行当前循环的statement, 运行下一个循环
函数
使用def()設定一個函数,return 为返回的结果
def demo(a):
print(a)
return a
#结果
>>> demo('try')
try
'try'