Python 學習筆記(十一)Python語句(二)

来源:https://www.cnblogs.com/wangruihua-521/archive/2018/03/15/8560899.html
-Advertisement-
Play Games

For 迴圈語句 基礎知識 for迴圈可以遍歷任何序列的項目,如一個列表或者一個字元串。 語法: for 迴圈規則: do sth 判斷對象是否可迭代 zip() 函數 函數用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。 如果各個迭代器的元素個數不一致 ...


For 迴圈語句

基礎知識

for迴圈可以遍歷任何序列的項目,如一個列表或者一個字元串。

語法:

for 迴圈規則:

  do sth

 1 >>> for i in "python" : #用i這個變數遍歷這個字元串的每一個字元
 2 ...     print i  #將遍歷的字元列印出來
 3 ...
 4 p
 5 y
 6 t
 7 h
 8 o
 9 n
10 >>> lst =["baidu","google","ali"] 
11 >>> for i in lst: #用變數i遍歷這個列表,將每個元素列印出來
12 ...     print i
13 ...
14 baidu
15 google
16 ali
17 >>> t =tuple(lst) 
18 >>> t
19 ('baidu', 'google', 'ali')
20 >>> for i in t: #用變數i遍歷元組,將每個元素列印出來
21 ...     print i
22 ...
23 baidu
24 google
25 ali
26 >>> d =dict([("lang","python"),("website","baidu"),("city","beijing")])
27 >>> d
28 {'lang': 'python', 'website': 'baidu', 'city': 'beijing'}
29 >>> for k in d: #用變數k遍歷這個字典,將每個key列印出來
30 ...     print k
31 ...
32 lang
33 website
34 city
35 >>> for k in d: #用變數k遍歷字典d
36 ...     print k,"-->",d[k]  #將key值和value值列印出來
37 ...
38 lang --> python
39 website --> baidu
40 city --> beijing
41 >>> d.items() #以列表返回可遍歷的(鍵, 值) 元組
42 [('lang', 'python'), ('website', 'baidu'), ('city', 'beijing')]
43 >>> for k,v in d.items(): #用key  value遍歷d.items()的元組列表
44 ...     print k,"-->",v   #取得key ,value
45 ...
46 lang --> python
47 website --> baidu
48 city --> beijing
49 >>> for k,v in d.iteritems():  iteritems 返回的是迭代器  推薦使用這個
50 ...     print k,v
51 ...
52 lang python
53 website baidu
54 city beijing
55 >>> d.itervalues()  返回的是迭代器 
56 <dictionary-valueiterator object at 0x0000000002C17EA8>
57 >>>

判斷對象是否可迭代

1 >>> import collections  #引入標準庫
2 >>> isinstance(321,collections.Iterable) #返回false,不可迭代
3 False
4 >>> isinstance([1,2.3],collections.Iterable) #返回true,可迭代
5 True
 1 >>> l =[1,2,3,4,5,6,7,8,9]
 2 >>> l[4:]
 3 [5, 6, 7, 8, 9]
 4 >>> for i in l[4:]: #遍歷4以後的元素
 5 ...     print i
 6 ...
 7 5
 8 6
 9 7
10 8
11 9
12 >>> help(range) #函數可創建一個整數列表,一般用在 for 迴圈中
13 Help on built-in function range in module __builtin__:
14 
15 range(...)
16     range(stop) -> list of integers
17     range(start, stop[, step]) -> list of integers  #計數從 start 開始,計數到 stop 結束,但不包括 stop,step:步長,預設為1
18 
19     Return a list containing an arithmetic progression of integers.
20     range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
21     When step is given, it specifies the increment (or decrement).
22     For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
23     These are exactly the valid indices for a list of 4 elements.
24 
25 >>> range(9) 
26 [0, 1, 2, 3, 4, 5, 6, 7, 8]
27 >>> range(2,8)
28 [2, 3, 4, 5, 6, 7]
29 >>> range(1,9,3)
30 [1, 4, 7]
31 >>> l
32 [1, 2, 3, 4, 5, 6, 7, 8, 9]
33 >>> range(0,9,2)
34 [0, 2, 4, 6, 8]
35 >>> for i in range(0,9,2):
36 ...    print i
37 ...
38 0
39 2
40 4
41 6
42 8
43 >>>
 1 #! /usr/bin/env python
 2 #coding:utf-8
 3 
 4 aliquot =[] #創建一個空的列表
 5 
 6 for n in range(1,100):   #遍歷1到100 的整數
 7     if n %3==0:          #如果被3整除
 8         aliquot.append(n) #將n值添加到列表中
 9 
10 print aliquot

zip() 函數

函數用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。

如果各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同,利用 * 號操作符,可以將元組解壓為列表。

返回一個列表,這列表是以元組為元素

 1 >>> a =[1,2,3,4,5]
 2 >>> b =[9,8,7,6,5]
 3 >>> c =[]
 4 >>> for i in range(len(a)):
 5 ...     c.append(a[i]+b[i])
 6 >>> for i in range(len(a)):
 7 ...     c.append(a[i]+b[i])
 8 ...
 9 >>> c
10 [10, 10, 10, 10, 10]
11 >>> help(zip)
12 Help on built-in function zip in module __builtin__:
13 
14 zip(...)
15     zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
16 
17     Return a list of tuples, where each tuple contains the i-th element
18     from each of the argument sequences.  The returned list is truncated
19     in length to the length of the shortest argument sequence.
20 
21 >>> a
22 [1, 2, 3, 4, 5]
23 >>> b
24 [9, 8, 7, 6, 5]
25 >>> zip(a,b)
26 [(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]
27 >>> c =[1,2,3]
28 >>> zip(c,b)
29 [(1, 9), (2, 8), (3, 7)]
30 >>> zip(a,b,c)
31 [(1, 9, 1), (2, 8, 2), (3, 7, 3)]
32 >>> d=[]
33 >>> for x,y in zip(a,b):
34 ...     d.append(x+y)
35 ...
36 >>> d
37 [10, 10, 10, 10, 10]
38 >>> r =[(1,2),(3,4),(5,6),(7,8)]
39 >>> zip(*r)
40 [(1, 3, 5, 7), (2, 4, 6, 8)]
41 >>>

enumerate()函數

函數用於將一個可遍歷的數據對象(如列表、元組或字元串)組合為一個索引序列,同時列出數據和數據下標,一般用在 for 迴圈當中。

語法:

enumerate(sequence, [start=0])  

sequence -- 一個序列、迭代器或其他支持迭代對象

start -- 下標起始位置。

返回值: enumerate枚舉對象

 1 >>> help(enumerate)
 2 Help on class enumerate in module __builtin__:
 3 
 4 class enumerate(object)
 5  |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 6  |
 7  |  Return an enumerate object.  iterable must be another object that supports
 8  |  iteration.  The enumerate object yields pairs containing a count (from
 9  |  start, which defaults to zero) and a value yielded by the iterable argument.
10  |  enumerate is useful for obtaining an indexed list:
11  |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
12  |
13  |  Methods defined here:
14  |
15  |  __getattribute__(...)
16  |      x.__getattribute__('name') <==> x.name
17  |
18  |  __iter__(...)
19  |      x.__iter__() <==> iter(x)
20  |
21  |  next(...)
22  |      x.next() -> the next value, or raise StopIteration
23  |
24  |  ----------------------------------------------------------------------
25  |  Data and other attributes defined here:
26  |
27  |  __new__ = <built-in method __new__ of type object>
28  |      T.__new__(S, ...) -> a new object with type S, a subtype of T
29 
30 >>> weeks =["sun","mon","tue","web","tue","fri","sta"]
31 >>> for i,day in enumerate(weeks):
32 ...     print str(i)+":"+day
33 ...
34 0:sun
35 1:mon
36 2:tue
37 3:web
38 4:tue
39 5:fri
40 6:sta
41 >>> for i in range(len(weeks)):
42 ...     print str(i)+":"+weeks[i]
43 ...
44 0:sun
45 1:mon
46 2:tue
47 3:web
48 4:tue
49 5:fri
50 6:sta
51 >>> raw ="Do you love canglaoshi? canglaoshi is a good teacher."
52 >>> raw_lst =raw.split(" ")
53 >>> raw_lst
54 ['Do', 'you', 'love', 'canglaoshi?', 'canglaoshi', 'is', 'a', 'good', 'teacher.']
55 >>> for i,w in enumerate(raw_lst):
56 ...     if w =="canglaoshi":
57 ...             raw_lst[i]="luolaoshi"
58 ...
59 >>> raw_lst
60 ['Do', 'you', 'love', 'canglaoshi?', 'luolaoshi', 'is', 'a', 'good', 'teacher.']
61 >>> for i,w in enumerate(raw_lst):
62 ...     if  "canglaoshi" in w:
63 ...             raw_lst[i]="luolaoshi"
64 ...
65 >>> raw_lst
66 ['Do', 'you', 'love', 'luolaoshi', 'luolaoshi', 'is', 'a', 'good', 'teacher.']
67 >>> a =range(10)
68 >>> a
69 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
70 >>> s =[]
71 >>> for i in a:
72 ...     s.append(i*i)
73 ...
74 >>> s
75 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
76 >>> b = [i*i for i in a] #列表解析
77 >>> b
78 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
79 >>> c = [i*i for i in a if i%3==0] #列表解析,加入限制條件
80 >>> c
81 [0, 9, 36, 81]
82 >>>

列表解析

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 看一次哭一次網址: https://www.bilibili.com/bangumi/play/ss836/?from=search&seid=4709676986893938334 4月出第二部! 聲臨其境,有一個人能配石頭門第22集嗎? 發Python上了,不喜歡求舉報 ...
  • 1. 啟動報錯,查看debug $ java -jar myproject-0.0.1-SNAPSHOT.jar –debug 2.自定義banner The banner that is printed on start up can be changed by adding a banner.t ...
  • While 迴圈語句 用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重覆處理的相同任務。 語法: 執行語句可以是單個語句或語句塊。判斷條件可以是任何表達式,任何非零、或非空(null)的值均為true。 當判斷條件假false時,迴圈結束。 示例:for迴圈實現猜字游戲 while 實 ...
  • 1. 字元串中必須僅有P, A, T這三種字元,不可以包含其它字元; 2. 任意形如 xPATx 的字元串都可以獲得“答案正確”,其中 x 或者是空字元串,或者是僅由字母 A 組成的字元串; 3. 如果 aPbTc 是正確的,那麼 aPbATca 也是正確的,其中 a, b, c 均或者是空字元串, ...
  • java.lang.IllegalArgumentExceptionat org.springframework.asm.ClassReader.<init>(Unknown Source)at org.springframework.asm.ClassReader.<init>(Unknown S ...
  • 練習 ...
  • 1.使用字元串來存儲文本; 2.在程式中顯示字元串; 3.在字元串中包含特殊的字元; 4.拼接字元串; 5.在字元串中包含變數; 6.比較字元串; 7.判斷字元串的長度; 程式Credits:顯示一部電影的導演和演員名單 1 package com.jsample; 2 3 public class ...
  • 網上有太多的VHDL和verilog比較的文章,基本上說的都是VHDL和verilog之間可以實現同一級別的描述,包括模擬級、寄存器傳輸級、電路級,所以可以認為兩者是等同級別的語言。很多時候會了其中一個,當然前提是真的學會,知道rtl(寄存器傳輸級)的意義,知道rtl與電路如何對應,在此基礎上,則很 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...