国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python -- 3. 操作列表

2019-11-08 01:33:04
字體:
來源:轉載
供稿:網友

1. 遍歷整個列表

magicians = ['alice', 'david', 'carolina']for magician in magicians: PRint(magician)

2. 避免縮進錯誤 Python根據縮進來判斷代碼行與前一個代碼行的關系。

忘記縮進 不必要的縮進 遺漏了冒號

3. 創建數值列表 (1).使用函數range() 函數range() 能夠輕松地生成一系列的數字,從你指定的第一個值開始數,并在到達你指定的第二個值前停止

for value in range(1,5): print(value)

(2).使用range() 創建數字列表 要創建數字列表,可使用函數list() 將range() 的結果直接轉換為列表。

numbers = list(range(1,6))print(numbers)

使用函數range() 時,還可指定步長

even_numbers = list(range(2,11,2))print(even_numbers)

(3).對數字列表執行簡單的統計計算

>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]>>> min(digits)0 >>> max(digits)9 >>> sum(digits)45

(4).列表解析 列表解析 將for 循環和創建新元素的代碼合并成一行,并自動附加新元素.

squares = [value**2 for value in range(1,11)]print(squares)

4. 使用列表的一部分(切片) 處理列表的部分元素——Python稱之為切片 (1).切片 要創建切片,可指定要使用的第一個元素和最后一個元素的索引,Python在到達你指定的第二個索引前面的元素后停止。

players = ['charles', 'martina', 'michael', 'florence', 'eli']print(players[0:3])

如果你沒有指定第一個索引,Python將自動從列表開頭開始:

players = ['charles', 'martina', 'michael', 'florence', 'eli']print(players[:4])

如果你沒有指定最后一個索引,則切片終止于列表末尾:

players = ['charles', 'martina', 'michael', 'florence', 'eli']print(players[2:])

(2).遍歷切片 如果要遍歷列表的部分元素,可在for 循環中使用切片。

players = ['charles', 'martina', 'michael', 'florence', 'eli']print("Here are the first three players on my team:")for player in players[:3]: print(player.title())

(3).復制列表 要復制列表,可創建一個包含整個列表的切片,方法是同時省略起始索引和終止索引([:] )

my_foods = ['pizza', 'falafel', 'carrot cake']friend_foods = my_foods[:]print("My favorite foods are:")print(my_foods)print("/nMy friend's favorite foods are:")print(friend_foods)

倘若我們只是簡單地將my_foods 賦給friend_foods ,就不能得到兩個列表。

my_foods = ['pizza', 'falafel', 'carrot cake']#這行不通friend_foods = my_foodsmy_foods.append('cannoli')friend_foods.append('ice cream')print("My favorite foods are:")print(my_foods)print("/nMy friend's favorite foods are:")print(friend_foods)

這種語法實際上是讓Python將新變量friend_foods 關聯到包含在my_foods 中的列表,因此這兩個變量都指向同一個列表。



5. 元組 Python將不能修改的值稱為不可變的 ,而不可變的列表被稱為元組。 元組看起來猶如列表,但使用圓括號而不是方括號來標識。 (1).定義元組

dimensions = (200, 50)print(dimensions[0])print(dimensions[1])

嘗試修改元組dimensions 中的一個元素,將出錯

dimensions = (200, 50)dimensions[0] = 250 #出錯

(2).遍歷元組中的所有值

dimensions = (200, 50)for dimension in dimensions: print(dimension)

(3).修改元組變量 雖然不能修改元組的元素,但可以給存儲元組的變量賦值。

dimensions = (200, 50)print("Original dimensions:")for dimension in dimensions: print(dimension)dimensions = (400, 100)print("/nModified dimensions:")for dimension in dimensions: print(dimension)
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 仙游县| 宜宾市| 洪湖市| 南漳县| 体育| 宜宾市| 新竹县| 磴口县| 鹤山市| 通州区| 灵丘县| 织金县| 扶风县| 乐都县| 永寿县| 抚远县| 东至县| 绥芬河市| 望江县| 垣曲县| 屯门区| 犍为县| 新干县| 封开县| 阳江市| 千阳县| 阿坝县| 岚皋县| 兴和县| 衢州市| 确山县| 宜都市| 本溪| 汨罗市| 靖江市| 察隅县| 平顺县| 神池县| 阿勒泰市| 皋兰县| 香港|