Five techniques for Python to derive from list to zip() function

爱喝马黛茶的安东尼
Release: 2019-10-25 17:56:00
forward
2524 people have browsed it

Five techniques for Python to derive from list to zip() function

In this article, the author introduces 5 methods. Maybe we don’t know much about them at the entry stage, but these 5 skills are very practical in actual combat.

String operations

A string is essentially a tuple, but there are many "operations" on strings. The most intuitive ones are the string and * operations, which represent repetition and concatenation respectively.

>>> my_string = "Hi Medium..!"
>>> print(my_string * 2)
Hi Medium..!Hi Medium..!
>>> print(my_string + " I love Python" * 2)
Hi Medium..! I love Python I love Python
Copy after login

In addition, if you want to get the reverse string, you can also directly use [::-1] for indexing:

>>> print(my_string[::-1])
!..muideM iH>>> my_list = [1,2,3,4,5]
>>> print(my_list[::-1])
[5, 4, 3, 2, 1]
Copy after login

If the list elements are all strings, then we can quickly Use the join() method to splice all the elements together:

>>> word_list = ["awesome", "is", "this"]
>>> print(' '.join(word_list[::-1]) + '!')
this is awesome!
Copy after login

As above, we use the .join() method to splice the list elements, where 『 』 indicates that the connection method is a space. In fact, in natural language processing, this method is often used. For example, if we split the sentence into characters, then the post-processing merge needs to use join().

Related recommendations: "Python Basic Tutorial"

List comprehension

If you don’t know how to use list comprehension yet , then learn it quickly. As the author of this article said, "When I first learned this method, my whole world changed." List comprehension is really very powerful. It is not only faster than ordinary methods, but also intuitive. , readability is very strong. If you want to iterate over a list and do some calculations, use it.

We start by defining a simple function that squares a variable and adds 5:

>>> def stupid_func(x):
>>>     return x**2 + 5
Copy after login

If we want to apply this function to odd items in the list, then list comprehensions are not used In the case of formula, we usually write it in the following form:

>>> my_list = [1, 2, 3, 4, 5]
>>> new_list = []
>>> for x in my_list:
>>>     if x % 2 != 0:
>>>         new_list.append(stupid_func(x))
>>> print(new_list)
[6, 14, 30]
Copy after login

But now that we have a list comprehension, the above code can be equivalently modified to:

>>> my_list = [1, 2, 3, 4, 5]
>>> print([stupid_func(x) for x in my_list if x % 2 != 0])
[6, 14, 30]
Copy after login

General syntax of list comprehension It can be expressed as [expression for item in list]. If you want to add some Boolean conditional statements, then the above syntax can be modified to [expression for item in list if conditional]. Its structure is actually equivalent to the following.

>>> for item in list:
>>>     if conditional:
>>>         expression
Copy after login

The above list comprehension can be further simplified, that is, there is no need to define a new function.

>>> print([x ** 2 + 5 for x in my_list if x % 2 != 0])
[6, 14, 30]
Copy after login

Lambda and Map

Lambda is an anonymous function, it may look a little strange, but once you understand it, it becomes Very intuitive and powerful.

Generally speaking, Lambda functions are relatively small, and they do not need to define function names. So why do you need anonymous functions? To put it simply, Lambda most often performs some intuitive operations. It does not require standard function definitions, and it does not require new function names to be called again.

Let’s take the above square plus 5 as an example. Earlier we defined a standard function, def stupid_func(x), now we can try the Lambda anonymous function:

>>> stupid_func = (lambda x : x ** 2 + 5)
>>> print([stupid_func(1), stupid_func(3), stupid_func(5)])
[6, 14, 30]
Copy after login

So why do we use the above expression? A large part of the reason is that when we want to perform some simple operations, we can do it without defining a real function. For example, to sort list elements, an intuitive way can be to use the sorted() method:

>>> my_list = [2, 1, 0, -1, -2]
>>> print(sorted(my_list))
[-2, -1, 0, 1, 2]
Copy after login

This can only sort from large to small or small to large by default, but with the help of Lambda expressions, we can achieve more freedom Sorting criteria. As shown below we want to sort the list according to the smallest square number, which can be defined using a Lambda function to tell the sorted() method how to sort.

>>> print(sorted(my_list, key = lambda x : x ** 2))
[0, -1, 1, -2, 2]
Copy after login

Map is a simple function that applies a function to some other sequence element, such as a list. If we have two lists and we want to multiply the corresponding elements of the two lists, we can quickly achieve this function using the lambda function and map:

>>> print(list(map(lambda x, y : x * y, [1, 2, 3], [4, 5, 6])))
[4, 10, 18]
Copy after login

The above code is very elegant, if you don’t use them both Or, then the general expression needs to be written like this:

>>> x, y = [1, 2, 3], [4, 5, 6]
>>> z = []
>>> for i in range(len(x)):
>>>     z.append(x[i] * y[i])
>>> print(z)
[4, 10, 18]
Copy after login

Single-line conditional statement

If we use conditional statements, then it is most likely to be written like this:

>>> x = int(input())
>>> if x >= 10:
>>>     print("Horse")
>>> elif 1 < x < 10:
>>>     print("Duck")
>>> else:
>>>     print("Baguette")
Copy after login

But in fact, we can also write all the conditions in the print function, that is, the above 7 lines of code can be equivalently written as the following line:

print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")
Copy after login

This looks really concise. If you look at what you wrote before There are really many codes that can be changed into this kind of expression.

zip()

When introducing the map() function earlier, we gave an example of applying a certain function to two parallel lists, and zip( ) function makes it easier to do this.

If we have two lists, the first list contains first names and the second list contains last names. Using the zip() function, we can splice them together as follows.

>>> first_names = ["Peter", "Christian", "Klaus"]
>>> last_names = ["Jensen", "Smith", "Nistrup"]
>>> print([&#39; &#39;.join(x) for x in zip(first_names, last_names)])
[&#39;Peter Jensen&#39;, &#39;Christian Smith&#39;, &#39;Klaus Nistrup&#39;]
Copy after login

In other words, zip turns two equal-length lists into one-to-one pairs, namely (("Peter", "Jensen"), ("Christian", "Smith"), ( "Klaus", "Nistrup")).

The above is the detailed content of Five techniques for Python to derive from list to zip() function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jianshu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template