日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python学习札记(十七) 高级特性3 列表生成式

發布時間:2023/12/10 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python学习札记(十七) 高级特性3 列表生成式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

參考:列表生成式

Note

1.List Comprehensions,即列表生成式,是Python中內置的非常強大的list生成式。

eg.生成一個列表:[1*1, 2*2, ..., 10*10]

使用for...in的方法:

#!/usr/bin/env python3L1 = []for i in range(1, 11) :L1.append(i*i)print(L1)

使用列表生成式:

L2 = [i*i for i in range(1, 11)]print(L2)

output:

sh-3.2# ./listcomprehensions1.py [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

2.列表生成式可以在后面加上條件判斷:

eg.符合 (i*i)%2==0 要求

L3 = [i*i for i in range(1, 11) if (i*i)%2 == 0]print(L3)

output:

[4, 16, 36, 64, 100]

3.也可以使用兩層循環:

L4 = [i+j for i in range(1, 11) for j in range(1, 11)]print(L4) [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] L5 = [i+j for i in 'ABC' for j in 'abc']print(L5) ['Aa', 'Ab', 'Ac', 'Ba', 'Bb', 'Bc', 'Ca', 'Cb', 'Cc']

4.使用列表生成式能簡化代碼,如輸出當前目錄的文件名:

import osL6 = [i for i in os.listdir('.')] # listdir()print(L6) ['listcomprehensions1.py']

5.對于dict來說,列表生成式也可以生成key-value的list:items()方法

dic = {'Chen': 'Student', '952693358': 'QQ', 'Never-give-up-C-X': 'WeChat'}L7 = [x+'='+y for x, y in dic.items()]print(L7) ['952693358=QQ', 'Chen=Student', 'Never-give-up-C-X=WeChat']

6.將字符串變成小寫字符串:lower()函數

str1 = 'HeyGirl'L8 = [i.lower() for i in str1]print(L8) ['h', 'e', 'y', 'g', 'i', 'r', 'l']

Practice

如果list中既包含字符串,又包含整數,由于非字符串類型沒有lower()方法,所以列表生成式會報錯:

>>> L = ['Hello', 'World', 18, 'Apple', None] >>> [s.lower() for s in L] Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 1, in <listcomp> AttributeError: 'int' object has no attribute 'lower'

使用內建的isinstance函數可以判斷一個變量是不是字符串:

>>> x = 'abc' >>> y = 123 >>> isinstance(x, str) True >>> isinstance(y, str) False

提供:L1 = ['Hello', 'World', 18, 'Apple', None]

期待輸出L2 = [L1中屬于字符串的元素的小寫]

Ans:

#!/usr/bin/env python3L1 = ['Hello', 'World', 18, 'Apple', None]L2 = [i.lower() for i in L1 if isinstance(i, str)]print(L2) sh-3.2# ./listcomprehensions2.py ['hello', 'world', 'apple']

2017/2/6

轉載于:https://www.cnblogs.com/qq952693358/p/6371395.html

總結

以上是生活随笔為你收集整理的Python学习札记(十七) 高级特性3 列表生成式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。