條件、循環和其它語句學習2

一、while循環,當條件爲真時,一直執行while裏的語句塊app

### 要求客戶輸入用戶名,直到客戶輸入名字結束函數

name =''
while not name:
name = input('please entre your name:')
print('hello,%s'%name)

可是有個問題 若是客戶輸入空格,程序也會把這個空格當成name處理,空格也是字符串,能夠用string.strip()去除name的兩端空格工具

name =''
while not name.strip():
name = input('please entre your name:')
print('hello,%s'%name)

二、for循環,遍歷序列sequence和字典(字典非可迭代),其餘可迭代對象spa

遍歷list3d

 

>>> a = [1,2,3,4]
>>> for i in a:
print(i)對象

1
2
3
4blog

 

遍歷tuple排序

>>> b = (1,2,3,4)three

 

>>> for i in b:
print(i)ip

1
2
3
4

 

遍歷字典

 

>>> d = {1:'one',2:'two',3:'three'}
>>> for item in d.items():  ###遍歷項
print(item)

(1, 'one')
(2, 'two')
(3, 'three')
>>> for k in d.keys(): ###遍歷key值
print(k)

1
2
3
>>> for v in d.values(): ###遍歷值
print(v)

one
two
three

 

>>> for k,v in d.items():###遍歷items,返回k,v
print(k,v)

1 one
2 two
3 three

三、一些迭代工具

並行迭代

 

>>> name = ['anne','beth','george','damon']
>>> age = [18,19,20,31]
>>> for i in range(len(name)):###range()返回迭代器
print(name[i],age[i])

 


anne 18
beth 19
george 20
damon 31

 

 zip函數,將多個序列合併成一個序列,返回一個zip對象,可迭代

 

>>> name = ['anne','beth','george','damon']
>>> age = [18,19,20,31]

>>> home = ['Beijing','Nanjing','Hangzhou','Kunming']

>>> zip(name,age,home)
<zip object at 0x0000020219B9E048>
>>> for item in zip(name,age,home):
    print(item)


('anne', 18, 'Beijing')
('beth', 19, 'Nanjing')
('george', 20, 'Hangzhou')
('damon', 31, 'Kunming')

>>> for n,a,h in zip(name,age,home):
    print(n,a,h)


anne 18 Beijing
beth 19 Nanjing
george 20 Hangzhou
damon 31 Kunming

 

zip能夠壓縮不一樣長度的序列,當短的序列壓縮完成後,則中止

 

>>> name = ['anne','beth','george','damon']
>>> age = [18,19]
>>> zip(name,age)
<zip object at 0x0000020219B9E188>
>>> for item in zip(name,age):
    print(item)

('anne', 18)
('beth', 19)

四、enumerate(iterable,start=0) 枚舉函數,第一參數爲可迭代的對象,第二個參數指定下標開始的數字,返回一個enumerate對象;

>>> name = ['anne','beth','george','damon']

 

>>> for index,n in enumerate(name,0):###指定index從0開始
    print(index,n)

index  n

0       anne
1       beth
2       george
3       damon

>>> for index,n in enumerate(range(3),1): ###指定index從1開始
    print(index,n)

1 0
2 1
3 2

五、翻轉和排序迭代,sorted()排序、reversed()翻轉,做用於任何序列或可迭代對象上,sorted()返回排序後的新列表;reversed()返回一個可迭代對象

 

>>> sorted([1,4,2,3,9,6])
[1, 2, 3, 4, 6, 9]
>>> reversed([1,3,2])
<list_reverseiterator object at 0x0000020219A079B0>
>>> list(reversed([1,3,2]))
[2, 3, 1]

>>> list(reversed('hello,world!'))
['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']
>>> ''.join(reversed('hello,world!'))
'!dlrow,olleh'

 

六、break跳出循環體,執行下面的語句塊,continue跳出當前循環,執行下一個循環(儘可能使用break)

 例子:求取100之內最大的平方值;那程序能夠從100向下迭代

 

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

 


81

for x in seq:

  if condition1: continue

  if condition2:continue

  do_something()

  do_something_else()

  etc()

能夠用下面的語句替換

for x in seq:

  if not(condition1 or condition2 or condition3):

    do_something()

    do_something_else()

    etc()

 

七、while True/Break語句

例子:### 要求客戶輸入用戶名,直到客戶輸入名字結束

 

>>> while True:
    name = input('please enter your name:')
      if name:
        print('hello,%s'%name)
        break
      else:
        continue

 

八、for循環中的else,僅在break未執行時,執行else語句塊

 

from math import sqrt
for n in range(99,81,-1):
root = sqrt(n)
if root == int(root):
print(n)
break
else:
print("Didn't find it")

九、列表推倒式,根據已經有的列表和條件,新建一個列表

###求取1-9的平方

 

>>> lis = []
>>> for i in range(10):
lis.append(i*i)

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

 

上面的新建lis列表的方式能夠改寫成列表推倒式[i*i for i in range(10)]

>>> [i*i for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 

>>> [i*i for i in range(10) if i%3==0] 添加新列表生成的條件
[0, 9, 36, 81]

多個for語句

 

>>> [(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 i in range(3):
for j in range(3):
result.append((i,j))

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

十、實例,將boys和girls列表中各名字首字母同樣的名字組合在一塊兒

 

>>> 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) ###將girls列表轉換成{首字母:[名字]}的字典,後面用列表是由於遍歷讀取時,名字能夠做爲一個元素整個讀取,不然默認string會分解成一個一個的letter,例如‘a’‘l’‘i’‘c’‘e’

>>> print(lettergirls)
{'a': ['alice'], 'b': ['bernice'], 'c': ['clarice']}

>>> [b+"+"+g for b in boys for g in lettergirls[b[0]]] ###根據遍歷獲得的b,直接從字典根據key取value值['chris+clarice', 'arnold+alice', 'bob+bernice']

相關文章
相關標籤/搜索