Python学习札记(十七) 高级特性3 列表生成式
生活随笔
收集整理的這篇文章主要介紹了
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 列表生成式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SeaTunnel
- 下一篇: python 爬虫002-http与ur