Categories

# python function | List of Formula

When writing a program or view someone else’s program, often encounter list generation type, this is not complicated to use, but very useful, to make our code more simple and flexible. Many users python and less likely to use it. Today, we give a detailed explanation using a list of formula and generator expressions

I. List generation

Pros: One line of code can handle almost any list needed

Disadvantages: easily fascinated, easy troubleshooting, no more than three cycles

List List derived by any of the formula can be constructed with other construct can be, for example, loop

List comprehension, for up to no more than three cycles. Only with a judge

1. circulation mode: Template: [processed through i for i in iterables]

Method using a for loop

```li = []
for i in range(1,4):
li.append('The first Fair Princess'+str(i)+'Ministry')

print(li)                   #[ 'A first Fair Princess', 'Fair Princess of 2', 'Fair Princess Part 3']```

The second way of writing

```li = []
for i in range(1,4):
li.append('% S of section Fair Princess' % i)

print(li)```

The above code, line can get. With a list comprehension on it

```li = ['% S of section Fair Princess' %i for i in range(1,4)]
print(li)

li = ['Section {{} of the Beizhuge'.format(i) for i in range(1,4)]         #Up and down the same result
print(li)```

Example: 1 – 10 square seeking results

```li = [i ** 2 for i in range(1,11)]
print(li) ```
`执行输出：[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]`

2. Screening Mode: [processed through i for i in iterables if screening conditions]

`Within 30 All numbers divisible by 3`
```l3 = [i for i in range(1,31) if i % 3 == 0]
print(l3)                         　　　　　　　　# [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]```
`All of the square of the number divisible by 3 can be less than 30`
```li = [i**2 for i in range(1,31) if i % 3 == 0]
print(li)                         　　　　　　　　# [9, 36, 81, 144, 225, 324, 441, 576, 729, 900]```
`Find all the names in the name list contains two nested 'e' of`
```names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry']]
l4 = [name for i in names for name in i if name.count('e') == 2 ]
print(l4)                         　　　　　　　　# ['Jefferson', 'Wesley', 'Steven', 'Jennifer']```

Is a list of commonly derived formula

Dictionary derivations

A dictionary of key value and swap

```dict = {'a': 10, 'b': 34}
dict_frequency = {dict[k]: k for k in mcase}
print(dict_frequency) ```
`执行输出：{10: 'a', 34: 'b'}`

Equivalent to

```dict = {'a': 10, 'b': 34}
dict_frequency = {}
for k in dict:
dict_frequency[k]=dict[k]

print(dict_frequency) ```
`If Key and value is the same, it is not suitable for the above code`

Set derivations

Square calculation of each value in the list, the weight comes to function

```squared = {x**2 for x in [1, -1, 2]}
print(squared)```
`执行输出：{1, 4}`
```a = {1,1,4}
print(type(a)) ```
`执行输出：　　结果是一个集合，它也是用{}表示的。`

And a collection of dictionaries is a difference:

Have key-value pairs, a dictionary, such as { ‘k1’: 1, ‘k1’: 2}

No key-value pairs is a collection, such as {1,2,3,4}

Second, the generator expression

Same as list derivation, except that [] is changed to ()

```l_obj = ('% S of section Fair Princess' % i for i in range(1,4))
print(l_obj)```
`结果是一个生成器对象： at 0x000002DDBEBADE60>`

Value method using __next__

```l_obj = ('% S of section Fair Princess' % i for i in range(1,4))

print(l_obj.__next__())
print(l_obj.__next__())
print(l_obj.__next__())```
```输出结果：

List comprehension: a glance, accounting memory

Generator expressions: inconvenient seen, save memory.