Python_8

  1. 1.
>>> sorted([1,2,3,2,1,3,4])
[1, 1, 2, 2, 3, 3, 4]
>>> sorted(['hello,world!'])
['hello,world!']
>>> sorted('hello,world!')
['!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello,world!'))
['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello,world!'))
'!dlrow,olleH'

翻转和排序迭代。

  1. 2.

from math import sqrt
for n in range(99,0,-1):
    root=sqrt(n)
    if  root==int(root):
        print n
        break

输出1到99最大的整数的平方数,此程序会输出81。range的第三个参数是反向迭代的步长。

  1. 3.
while True:
    word=raw_input('Please input a word:')
    if not word:
        break
    print  'Your input word is',word 

输入一个单词,直到输入回车符为止。

Please input a word:ss
Your input word is ss
Please input a word:dd
Your input word is dd
Please input a word:    
Your input word is     
Please input a word:s
Your input word is s
Please input a word:
  1. 4.
from math import sqrt
for n in range(99,81,-1):
    root=sqrt(n)
    if  root==int(root):
        print n
        break
else:
    print 'Dont\'t find it!'

这里的else,仅在for循环中没有调用break时执行。

Dont't find it!
  1. 5.
>>> [x*x for x in range(1,10)]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(1,10) if x%3==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)]

列表推导式。
使用以下代码同样可以完成上面的第三件事情。


result=[]
for x in range(3):
    for y in range(3):
        result.append((x,y))
print result

看起来比上面的代码要麻烦不少。

girls=['Lob','Jlice','Mary']
boys=['Lily','John','Jack']
same=[a+'+'+b for a in girls for b in boys if a[0]==b[0]]
print same

此处列表推导式的使用感觉很巧妙,比较了两组人名,将首字母相同的放在一组。
输出结果:

['Lob+Lily', 'Jlice+John', 'Jlice+Jack']
  1. 6.
>>> pass
>>> 

pass语句,当不知道这个方向的分支具体该怎么写时,可用pass。

>>> x=[1,2,3]
>>> y=x
>>> del x
>>> y
[1, 2, 3]
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

这里的del仅仅是删除了x这个名字。

  1. 7.
from math import sqrt
scope={}
exec 'sqrt=1' in scope
print sqrt(4)
print scope.keys()

这里涉及到了动态创建代码并执行,exec用来执行字符串中的代码,这里用scope这个字典来充当命名空间的作用,以免和本身的代码产生冲突。

输出结果:

2.0
['__builtins__', 'sqrt']
  1. 8.
>>> scope={}
>>> scope['x']=2
>>> scope['y']=3
>>> eval('x+y',scope)
5
>>> scope={}
>>> exec 'x=2' in scope
>>> eval('x*x',scope)
4

这里有两个例子初探作用域,eval会返回值,exec则不会。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值