久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

Python在方括號中使用for循環(huán),,類似[0foriinrange(10)],,叫列表解析...

 喜歡喝湯的八戒 2021-01-02

作者博文地址:https://www.cnblogs.com/liu-shuai/

列表解析

  根據(jù)已有列表,,高效創(chuàng)建新列表的方式。

  列表解析是Python迭代機制的一種應用,,它常用于實現(xiàn)創(chuàng)建新的列表,,因此用在[]中。

語法:

  [expression for iter_val in iterable]

  [expression for iter_val in iterable if cond_expr]

實例展示:

1 要求:列出1~10所有數(shù)字的平方 2 #################################################### 3 1,、普通方法: 
4 >>> L = [ ] 
5 >>> for i in range(1,11): 
6 ... L.append(i**2
7 ... 
8 >>> print L 9 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100
10 #################################################### 11 
2,、列表解析 
12 >>>L = [ i**2 for i in range(1,11)] 
13 >>>print L 14 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
 1 要求:列出1~10中大于等于4的數(shù)字的平方 2 #################################################### 3 1、普通方法:  4 >>> L = []  5 >>> for i in range(1,11):  6 ... if i >= 4:  7 ... L.append(i**2)  8 ...  9 >>> print L 10 [16, 25, 36, 49, 64, 81, 100] 11 #################################################### 12 2,、列表解析 13 >>>L = [ i**2 for i in range(1,11) if i >= 4 ] 14 >>>print L 15 [16, 25, 36, 49, 64, 81, 100]
1 要求:列出1~10所有數(shù)字的平方除以2的值 2 #################################################### 3 1,、普通方法 4 >>> L = [] 5 >>> for i in range(1,11): 6 ... L.append(i**2/2) 7 ... 8 >>> print L 9 [0, 2, 4, 8, 12, 18, 24, 32, 40, 50] 10 #################################################### 11 2、列表解析 12 >>> L = [i**2/2 for i in range(1,11) ] 13 >>> print L 14 [0, 2, 4, 8, 12, 18, 24, 32, 40, 50]
 1 要求:列出'/var/log'中所有已'.log'結尾的文件  2 ##################################################  3 1,、普通方法  4 >>>import os  5 >>>file = []  6 >>> for file in os.listdir('/var/log'):  7 ... if file.endswith('.log'):  8 ... file.append(file)  9 ... 10 >>> print file 11 ['anaconda.ifcfg.log', 'Xorg.0.log', 'anaconda.storage.log', 'Xorg.9.log', 'yum.log', 'anaconda.log', 'dracut.log', 'pm-powersave.log', 'anaconda.yum.log', 'wpa_supplicant.log', 'boot.log', 'spice-vdagent.log', 'anaconda.program.log'] 12 ################################################## 13 2.列表解析 14 >>> import os 15 >>> file = [ file for file in os.listdir('/var/log') if file.endswith('.log') ] 16 >>> print file 17 ['anaconda.ifcfg.log', 'Xorg.0.log', 'anaconda.storage.log', 'Xorg.9.log', 'yum.log', 'anaconda.log', 'dracut.log', 'pm-powersave.log', 'anaconda.yum.log', 'wpa_supplicant.log', 'boot.log', 'spice-vdagent.log', 'anaconda.program.log']
1 要求:實現(xiàn)兩個列表中的元素逐一配對,。 2 1、普通方法: 3 >>> L1 = ['x','y','z'] 4 >>> L2 = [1,2,3] 5 >>> L3 = [] 6 >>> for a in L1: 7 ... for b in L2: 8 ... L3.append((a,b)) 9 ... 10 >>> print L3 11 [('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)] 12 #################################################### 13 2,、列表解析: 14 >>> L1 = ['x','y','z'] 15 >>> L2 = [1,2,3] 16 L3 = [ (a,b) for a in L1 for b in L2 ] 17 >>> print L3 18 [('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]
1 使用列表解析生成 9*9 乘法表2 3 print('\n'.join([''.join(['%s*%s=%-2s '%(y,x,x*y)for y in range(1,x+1)])for x in range(1,10)]))

說明:

  以上實例,,使用列表解析比使用普通方法的速度幾乎可以快1倍。因此推薦使用列表解析。

https://docs./3/tutorial/datastructures.html#list-comprehensions

5.1.3. List Comprehensions

List comprehensions provide a concise way to create lists.Common applications are to make new lists where each element is the result ofsome operations applied to each member of another sequence or iterable, or tocreate a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like:

>>>
>>> squares = []>>> for x in range(10):... squares.append(x**2)...>>> squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Note that this creates (or overwrites) a variable named x that still existsafter the loop completes. We can calculate the list of squares without anyside effects using:

squares = list(map(lambda x: x**2, range(10)))

or, equivalently:

squares = [x**2 for x in range(10)]

which is more concise and readable.

A list comprehension consists of brackets containing an expression followedby a for clause, then zero or more for or ifclauses. The result will be a new list resulting from evaluating the expressionin the context of the for and if clauses which follow it.For example, this listcomp combines the elements of two lists if they are notequal:

>>>
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y][(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and it’s equivalent to:

>>>
>>> combs = []>>> for x in [1,2,3]:... for y in [3,1,4]:... if x != y:... combs.append((x, y))...>>> combs[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Note how the order of the for and if statements is thesame in both these snippets.

If the expression is a tuple (e.g. the (x, y) in the previous example),it must be parenthesized.

>>>
>>> vec = [-4, -2, 0, 2, 4]>>> # create a new list with the values doubled>>> [x*2 for x in vec][-8, -4, 0, 4, 8]>>> # filter the list to exclude negative numbers>>> [x for x in vec if x >= 0][0, 2, 4]>>> # apply a function to all the elements>>> [abs(x) for x in vec][4, 2, 0, 2, 4]>>> # call a method on each element>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']>>> [weapon.strip() for weapon in freshfruit]['banana', 'loganberry', 'passion fruit']>>> # create a list of 2-tuples like (number, square)>>> [(x, x**2) for x in range(6)][(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]>>> # the tuple must be parenthesized, otherwise an error is raised>>> [x, x**2 for x in range(6)]  File '<stdin>', line 1, in <module>    [x, x**2 for x in range(6)]               ^SyntaxError: invalid syntax>>> # flatten a list using a listcomp with two 'for'>>> vec = [[1,2,3], [4,5,6], [7,8,9]]>>> [num for elem in vec for num in elem][1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehensions can contain complex expressions and nested functions:

>>>
>>> from math import pi>>> [str(round(pi, i)) for i in range(1, 6)]['3.1', '3.14', '3.142', '3.1416', '3.14159']

    本站是提供個人知識管理的網(wǎng)絡存儲空間,,所有內容均由用戶發(fā)布,,不代表本站觀點。請注意甄別內容中的聯(lián)系方式,、誘導購買等信息,,謹防詐騙。如發(fā)現(xiàn)有害或侵權內容,,請點擊一鍵舉報,。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多