Python 菜鸟学习第八课

时间:2022-10-15 16:35:32

翻转和排序迭代

>>>sorted([4,3,6,8,3])

[3,3,4,6,8]

>>>sorted('Hello, world!')

[' ', '!', ',', 'H', 'd', 'e', '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.跳出循环

1.1break

from math import sqrt

for n in range(99,0,-1)

      root = sqrt(n)

      if root == int(root):

               print n

               break

输出81

>>>range(0,10,2)

[0,2,4,6,8]

1.2continue

1.3 while True/break

while True:

     word = raw_input('Please enter a word: ')

     if not word: break

     print 'The word was ' + word

 

循环中的else字句

broke_out = False

for x in seq:

     do_something(x)

     if condition(x):

                 broke_out = True

                 break

      do_something_else(x)

if not broke_out:

       print "I didn't break out!"

 

for math import sqrt

for n in range(99,81,-1)

      root = sqrt(n)

      if root == int(root):

            print n

            break

else:

       print "Did't find it!"

列表推导式----轻量级循环

>>>[x*x for x in range(10)]

[0,1,4,9,16,25,36,49,64,81]

>>> [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)]

或者

result = []

for x in range(3):

     for y in range(3):

                 result.append((x,y))

>>>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']

 

三人行:

1.pass

>>>pass#什么都没发生

if name == 'Ralph Auldus Melish':

       print 'Welcome!'

elif name == 'Enid':

        # 还没玩.....

        pass

elif name == 'Bill Gates':

        print 'Access Denied'

2.del

3.exec/eval

3.1exec

>>> exec "print 'Hello, world!'"

Hello, world!

>>> from math import sqrt

>>>exec "sqrt =1"

>>>sqrt(4)

TypeError:

>>>from math import sqrt

>>>scope = {}

>>>exec 'sqrt=1' in scope

>>>sqrt(4)

2.0

>>>scope['sqrt']

1

>>>len(scope)

2

>>>scope.keys()

['sqrt','__builtins__']

eval

>>>eval(raw_input('Enter a arithmetic expression: '))

Enter an arithmetic expression: 6 + 18*2

42

 

>>>scope = {}

>>>scope['x']=2

>>>scope['y']=3

>>>eval('x*y',scope)

6

>>>scope = {}

>>>exec 'x=2' in scope

>>>eval ('x*x',scope)

4