# python sequence list derivation real column

1. List derivation list derivation can form a new list very succinctly: only a simple expression can transform the elements.

Format: [expression for variable in list] or [expression for variable in list if condition]

Filter conditions are optional, depending on the actual application, leaving only expressions

```>>> list =[x*x for x in range(10)]
Amount to
>>> alist= []
>>> for x in range(10):
Also equivalent to
>>> list= list(map(lambda x:x*x,range(10)))```

2. Avanti plays chess with the king. The king says that if izji loses, he can take whatever Avanti wants. Avanti said that we should order rice. There are 64 small squares on the chessboard. In the third one, we put four grains of rice, in the fourth one, we put eight grains of rice, and so on. The rice in each lattice behind is twice that in the previous one, and we always put 64 squares full. How many grains of rice do you need?

```>>> sum([2**i for i in range(64)])
18446744073709551615```

3. Use list derivation to realize the tiling of nested list

```>>> 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]Amount to
>>> vec=[[1,2,3],[4,5,6],[7,8,9]]
>>> result =[]
>>> for elem in vec:
for num in elem:
result.append(num)
>>> result
[1，2，3，4，5，6，7，8，9]```

4. If you do not use list derivation, you can do so.

```>>> vec=[[1,2,3],[4,5,6],[7,8,9]]
>>> sum(vec,[])
[1, 2, 3, 4, 5, 6, 7, 8, 9]or>>> vec=[[1,2,3],[4,5,6],[7,8,9]]>>> from itertools import chain>>> list(chain(*vec))[1, 2, 3, 4, 5, 6, 7, 8, 9]```

5. List all python source files in the current folder

```>>> import os
>>> [filename for filename in os.listdir('.')if filename.endswith(('.py','.pyw'))]Filter unqualified elements>>> list = [-1,-4,6,7,5,-2,3,9,-11]>>> >>> [i for i in list if i>0][6, 7, 5, 3, 9]```

6. It is known that there is a dictionary containing the scores of some students, calculating the highest score, the lowest score and the average score, and finding all the students with the highest score.

```>>> scores={"zhangsan":45,"lisi":78,"wangwu":40,"zhouliu":96,"zhaoqi":65,"sunba":90,"zhengjiu":78,"wushi":99,"dongshiyi":60}
>>> heighest=max(scores.values())
>>> lowest = min(scores.values())>>> average=sum(scores.values())*1.0/len(scores)
>>> heighest,lowest,average
(99, 40, 72.33333333333333)
>>> heighestPerson=[name for name,score in scores.items()if score == heighest]
>>> heighestPerson
['wushi']```

7. Multiple loops are used in list derivation to realize combination of multiple sequence elements, and specific elements can be filtered by combining conditional statements

```>>> [(x,y)for x in range(3) for y in range(2)]
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
>>> [(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)]```

Tags: Python Lambda

Posted on Sun, 22 Mar 2020 07:53:38 -0700 by peachsnapple