程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python list derivation and dictionary derivation

編輯:Python

List derivation and dictionary derivation

stay Python The derivation in is a very Pythonic Knowledge , This blog will give you a detailed answer to the technical knowledge related to list derivation and dictionary derivation .

List derivation

List derivation can use list , Tuples , Dictionaries , Sets and other data types , Quickly generate a list of specific needs .

The syntax is as follows :

[ expression for Iterative variable in Iteratable object if Conditional expression ]

if Conditional expression Non essential election , After learning the list derivation , You can see that it is for A variant of the loop , For example, we have a requirement to change all elements in a list into original values 2 times .

for Cyclic writing

my_list = 1,2,3

new_list = []

for i in my_list:

new_list.append(i*2)

print(new_list)

List derivation

nn_list = i*2 for i in my_list

print(nn_list)

Whether to compare or not is to for After the loop statement is deformed , Added one [], But here's the thing , The final result of each derivation will be a new list .

Let's look at the syntax of list derivation nn_list = i*2 for i in my_list ,for The keyword is followed by an ordinary loop , The previous expression i*2 Among them i Namely for Variables in the loop , In other words, the expression can be used after for Variables generated by loop iteration , By understanding the derivation of this content list, you have mastered 9 It's content , The rest is about proficiency .

Will be if Statements are included in the code , After running , You can also master the basic skills ,if A statement is a judgment , among i It is also the iteration variable generated by the previous loop .

nn_list = i*2 for i in my_list if i>1

print(nn_list)

These are general skills , Support two-tier derivation for loop , For example, the following code :

nn_list = (x,y) for x in range(3) for y in range(3)

print(nn_list)

Of course, if you want to encrypt ( No one can understand your code ) Your code , You can go on forever , The list derivation does not limit the number of cycle layers , Multi layer loops are nested layer by layer , You can expand a three-tier list derivation , It's all clear

nn_list = (x,y,z,m) for x in range(3) for y in range(3) for z in range(3) for m in range(3)

print(nn_list)

Of course, in the multi-layer list derivation , Still support if sentence , also if You can use the variables generated by all previous iterations later , However, it is not recommended to exceed 2 become , Beyond that, it will greatly reduce the readability of your code .

Of course, if you want your code to be more difficult to read , The following expressions are correct .

nn_list = (x, y, z, m) for x in range(3) if x > 1 for y in range(3) if y > 1 for z in range(3) for m in range(3)

print(nn_list)

nn_list = (x, y, z, m) for x in range(3) for y in range(3) for z in range(3) for m in range(3) if x > 1 and y > 1

print(nn_list)

nn_list = (x, y, z, m) for x in range(3) for y in range(3) for z in range(3) for m in range(3) if x > 1 if y > 1

print(nn_list)

Now you have a more intuitive concept of list derivation , The corresponding English of the list derivation is list comprehension, In some places, write list analytic expressions , Based on its final result , It's a syntax for creating lists , And it's a very concise grammar .

There are two different ways of writing , Then we have to compare efficiency , After testing, small data range has little impact , When the number of cycles reaches ten million , There are some differences .

import time

def demo1():

new_list = []
for i in range(10000000):
 new_list.append(i*2)

def demo2():

new_list = [i*2 for i in range(10000000)]

s_time = time.perf_counter()

demo2()

e_time = time.perf_counter()

print(" Code run time :", e_time-s_time)

Running results :

for loop

Code run time : 1.3431036140000001

List derivation

Code run time : 0.9749278849999999

stay Python3 The list derivation in has local scope , Variables and assignments inside expressions work only locally , A variable with the same name in the context of an expression can also be referenced normally , Local variables don't affect them . So it won't have the problem of variable leakage . For example, the following code :

x = 6

my_var = x*2 for x in range(3)

print(my_var)

print(x)

List derivation also supports nesting

The reference codes are as follows , Only unexpected , Nothing is impossible .

my_var = [y4 for y in [x2 for x in range(3)]]

print(my_var)

Dictionary derivation

With the concept of list derivation , Dictionary derivation is very simple to learn , The syntax is as follows :

{ key : value for Iterative variable in Iteratable object if Conditional expression }

Just look at the case directly

my_dict = {key: value for key in range(3) for value in range(2)}

print(my_dict)

The result is as follows :

{0: 1, 1: 1, 2: 1}

At this time, it should be noted that there can be no words with the same name in the dictionary key, The second occurrence overwrites the first value , So what you get value All are 1.

The most common is the following code , Traverse an iteratable object with key value relationship .

my_tuple_list = ('name', ' Eraser '), ('age', 18),('class', 'no1'), ('like', 'python')

my_dict = {key: value for key, value in my_tuple_list}

print(my_dict)

Tuple derivation and set derivation

In fact, you should be able to guess , stay Python There are these two derivations in , And I believe you have mastered the grammar . But the grammar is similar , But the result of tuple derivation is different , As follows .

my_tuple = (i for i in range(10))

print(my_tuple)

The result after running :

<generator object <genexpr> at 0x0000000001DE45E8>

The result generated using tuple derivation is not a tuple , It's a generator object , You need to pay special attention to , This writing method is called generator syntax in some places , Not called tuple derivation .

There is also a need to pay attention to the derivation of sets , Look at the code first :

my_set = {value for value in 'HelloWorld'}

print(my_set)

Because the set is unordered and not repeated , So it will automatically remove the duplicate elements , And the order of each run is different , It's easy to faint when using .

The summary of this blog

This blog , We learned the list and dictionary derivation , After mastering and skillfully applying the two , you Python The skill has taken another step forward .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved