博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python语句
阅读量:4221 次
发布时间:2019-05-26

本文共 1740 字,大约阅读时间需要 5 分钟。

>>> values
(1, 2, 3)
>>> x,y,z=values
>>> x
1
>>> y
2
>>> z
3

函数可以返回一个以上的值,打包成tuple。接受数量要一致。

is是同一性预算符。

>>> x=y=[1,2,3]

>>> z=[1,2,3]
>>> x is y
True
>>> x is z
False
>>> 因为x和y绑定到同一个列表上。z在另一个列表上。

不要用is比较 数值和字符串这类不可变值。结果不可预测。

short-circuit logic , lazy evaluation 避免执行无用代码。

a if b else c

>>> age =-1

>>> assert 0 < age <100, 'adfsdf'

Traceback (most recent call last):
  File "<pyshell#126>", line 1, in <module>
    assert 0 < age <100, 'adfsdf'
AssertionError: adfsdf

xrange一次只创建一个。大的序列是更高效。python3.0 range 会被转换成xrange风格的函数。什么意思?

>>> d

{'y': 2, 'x': 1, 'z': 3}
>>> for key, value in d.items():
print(key ,value)
y 2
x 1
z 3
>>> 

>>> name=['a','b','c']

>>> age=[12,34,56]
>>> zip(name, age)
<zip object at 0x00000000034F8D08>
>>> list(zip(name,age))
[('a', 12), ('b', 34), ('c', 56)]
>>> 

zip可以用在不等长的序列,最短序列用完停止

>>> list(zip(range(5), range(100)))

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> 

>>> strings=['adfsdf','xxxxx']

>>> for index, string in enumerate(strings): 可以迭代 索引-值对
if 'xxx' in string:
strings[index] = '[censored]'
>>> strings
['adfsdf', '[censored]']
>>> 

>>> [x*x for x in range(10) if x%3==0]
[0, 9, 36, 81]

>>> [(x,y) for x in range(3) for y in range(3)]

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

>>> girls=['alice','bernice','clarice']

>>> boys=['chris','arnold','bob']

>>> [b + "+" + g for b in boys for g in girls if b[0]==g[0]]

['chris+clarice', 'arnold+alice', 'bob+bernice']

更高效率如下:

>>> girls=['alice','bernice','clarice']>>> boys=['chris','arnold','bob']>>> letterGirls={}>>> for girl in girls:	letterGirls.setdefault(girl[0], []).append(girl)# 返回时是空list,在append,精准对应,不用像上面每次都循环	>>> print([b + '+' + g for b in boys for g in letterGirls[b[0]]])['chris+clarice', 'arnold+alice', 'bob+bernice']

转载地址:http://jqmmi.baihongyu.com/

你可能感兴趣的文章
Netty框架学习之路(五)—— EventLoop及事件循环机制
查看>>
MyBatis的缓存机制
查看>>
Java中的锁及AQS实现原理
查看>>
MySQL索引及优化
查看>>
MySQL的锁问题
查看>>
Java并发容器及其实现原理
查看>>
JVM调优方法
查看>>
MySQL的高可用
查看>>
Spring的注解驱动开发
查看>>
NoSQL数据库之Redis
查看>>
从IO-BIO-NIO-AIO-到Netty
查看>>
手写一个简易跳表(Java版)
查看>>
深入理解Redis
查看>>
SpringMVC实战与源码分析
查看>>
计算机操作系统--文件管理
查看>>
设计模式之行为型模式
查看>>
设计模式之结构型模式
查看>>
Java的反射机制
查看>>
HashMap源码分析
查看>>
LinkedList源码分析
查看>>