聊聊python

python基础知识纵览(中)

2017-09-07  本文已影响14人  疾风先生

python语句语法

程序块与作用域

#!/usr/bin/env python       ## 脚本设置env启动,env可以在系统的PATH查找
# -*- coding: UTF-8 -*-     ## 设置当前python的字符编码

def fn():
    print("python3.0")      ## python3.0 的打印输出
    print "python2.7"       ## python2.7 的打印输出

每个使用冒号":"标记的程序块内的代码必须有相同的描述

判断语句

a = 9
b = 4
c = None

## 第一种形式
if not c:       ## c不是None的时候执行if下的语句
    pass        ## 表示需要写代码但是实际什么也不做的场合        

if a > b:
    pass

if c is None:
    pass
    
## 第二种形式
if a > b:
    print("a > b")     ## python3.x的打印
else:
    print("a <= b")    

## 第三种形式
if a >= 10:
    print("a > 10")
elif 5 < a < 10:        ## ==> a > 5 and a < 10
    print("5 < a < 10")
else:
    print("a <= 5")
    
## 第四种形式
a = 9
b = 2
num = a if a > 10 else b        ##num is b 

循环语句

## 基本格式
while test:
    statement1
else:
    statement2

## 例子
children = ["tom","keithl","jane","mani","bob"]

while len(children) > 0:
    print "pop the child[%s]" % children.pop()
else:
    print("there have not any ele in chidlren ...")

pop the child[bob]
pop the child[mani]
pop the child[jane]
pop the child[keithl]
pop the child[tom]
## 基本格式
for target in object: 
    statements
else:
    statements

## 示例
>>> for x in ["spam", "eggs", "ham"]: 
... print(x, end=' ')
...
spam eggs ham

## 遍历带有元组信息的列表
>>> T = [(1, 2), (3, 4), (5, 6)]
>>> for (a, b) in T: # Tuple assignment at work
...     print(a,b)
... 
1 2 
3 4 
5 6

## 遍历字典
D = {'a': 1, 'b': 2, 'c': 3}
## 遍历字典方法1
for key in D:
    print(key, '=>', D[key])

## 遍历字典方法2
for (key, value) in D.items():
    print(key, '=>', value)
    
## 使用python3.x遍历并序列解压
for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]:
    print(a, b, c)

赋值语句

## 基本赋值
>>> num = 1
>>> wind = 9
>>> A,B = num,wind
>>> A,B
(1,9)

## 高级赋值
>>> str = "ABCD"
>>> a,b,c = str[0],str[1],str[2]
>>> a,b,c = list(str[:2]) + [str[2:]]
>>>(a,b),c = str[:2],str[2:]
>>> a,b,c = range(3)    ## 将三个变量名设置为整数0、1、2

## python3.x扩展序列解包
>>> seq = [1,2,3,4]
>>> a,*b = seq
>>> a
1
>>> b
[2,3,4]

>>> *a,b = seq
>>> a
[1,2,3]
>>> b
[4]

>>> a,*b,c = seq
>>> a
1
>>> b
[2,3]
>>> c
4

>>> a,b,*c = seq
>>> a
1 
>>> b
2
>>> c
[3,4]

总结:python3.x带""总是向其赋值一个列表,即使是匹配单个项,如果没有匹配会返回一个空的列表*

表达式语句

## 常用表达式
fn(args)            ## 函数调用
obj.call(args)      ## 对象方法调用
spam                ## 交互模式下打印变量
print(str)          ## python3.x打印操作
yiled x ** 2        ## 产生表达式语句

## 使用函数表达式并改变值
>>> L = [1,2,3]
>>> L.append(4)
>>> L
1,2,3,4

## python3.x之print函数打印格式
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout][, flush=False])
sep:是在每个对象之间插入
end:在文本打印之后追加end的字符串信息
file:将信息输出到指定的终端,默认是sys.stdout,即控制台
flush:py3.3新增特性,即设置为True时立即将信息刷新到输出流的目的终端上而无须等待

## 示例
>>> print(x, y, z, sep=', ') 
spam, 99, ['eggs']

## 将信息输出到data.txt中
>>> print(x, y, z, sep='...', file=open('data.txt', 'w'))

## 兼容python2.x和python3.x的print函数,导入以下包
from __future__ import print_function

迭代器

如果对象是实际保存的序列,或者可以在迭代工具中for一次产生一个结果的对象则称为可迭代

## 基本迭代器
for x in [1, 2, 3, 4]: 
    print(x ** 2, end=' ')

## 文件迭代器
## 第一种方式
for line in open('script2.py'):
    print(line.upper(), end='')

## 第二种方式
for line in open('script2.py').readlines():
    print(line.upper(), end='')

## 第三种方式
f = open('script2.py')
while True:
    line = f.readline()
    if not line: break 
    print(line.upper(), end='')


## 手动设置迭代器iter和next
L = [1, 2, 3]
I = iter(L)
while True:
    try:
        X = next(I)
    except StopItration:
        break
    print(X ** 2,end=' ')

## 内建迭代器类型,字典
D = {'a':1, 'b':2, 'c':3}
for key in D.keys():
    print(key, D[key])
    
## 列表解析
x = [y + 10 for y in range(10)]

## 文件列表解析
lines = [line for line in open("data.txt")]

## 扩展的列表解析
lines = [line for line in open("data.txt") if line[0] == "k"]   ## for循环下带有if语句块
list = [x + y for x in range(10) for y in range(5)]             ## for循环嵌套for循环

python3.x新增迭代器

## range迭代器
>>> R = range(10)
>>> I = iter(R)
>>> next(I)     ## 每次调用next就会输出列表的下一个元素


## map迭代器:map(func, *iterables):接受一个函数和一个迭代器对象,将所有的迭代器对象经过函数处理得到一个新的迭代对象数据
num = map(abs,(-2,-3,-5,9,3))
for n in num:
    print(n,end=",")
2,3,5,9,3,

## zip迭代器:zip(iter1, iter2=None, *some):第一个参数必填,接受可以迭代的对象,并将每组对象的对应元素重新组成tuple
z = zip((1,2,3),(5,6,7))
for pair in z:
    print(pair)
(1, 5),(2, 6),(3, 7),

## filter迭代器:filter(filter_fn,*iterables):接受一个函数和一个迭代对象,将符合函数filter_fn要求的将返回迭代数据
list(filter(bool, ['spam', '', 'ni']))  < = > [x for x in ['spam', '', 'ni'] if bool(x)]
上一篇 下一篇

猜你喜欢

热点阅读