Home  >  Article  >  Backend Development  >  Nine one-liners of Python code you should know and know

Nine one-liners of Python code you should know and know

WBOY
WBOYforward
2023-04-13 23:25:011608browse


When we start learning Python, we usually prioritize writing code that can get the job done, without paying attention to the readability of the code and the simplicity and efficiency of the code.

To be precise, this is perfectly fine, but there are ways to shorten our Python code without compromising readability. Single lines of Python code, as long as we can use them correctly, then we will be able to achieve both conciseness and readability!

Nine one-liners of Python code you should know and know

The following are 9 single-line codes that any student learning Python should know. Let’s take a look~

1. If — Else statement

The if-else statement is one of the first statements we learn in Python and is used to perform the true or false part of a given condition.

We use this statement a lot, but did you know it can be reduced to one line of code? In many cases, we can put if and else statements on the same line.

age = 18
valid = "You're an adult"
invalid = "You're NOT an adult"
print(valid) if age >= 18 else print(invalid)

2. Create a new list based on an existing list

Lists are a common way of storing data, but did you know that you can create a new list based on an existing list with just one line of code?

Yes, it's called a list comprehension and it provides a short syntax for creating a list based on the values ​​of an existing list. List comprehensions are more compact than the functions and loops used to make lists.

Here’s the syntax:

[expression for item in list]

Let’s look at an example:

words = ['united states', 'brazil', 'united kingdom']

capitalized = [word.title() for word in words]
>>> capitalized
['United States', 'Brazil', 'United Kingdom']

The code above does look better! But remember, we should keep the code user-friendly, so writing long list comprehensions in one line of code is not recommended.

3. Dictionary derivation

Similar to list derivation, there is also dictionary derivation in Python. Dictionary comprehension provides a short syntax for creating a dictionary in a single line of code.

The following is the syntax:

{key: value for key, value in iterable}

Let’s give a chestnut:

dict_numbers = {x:x*x for x in range(1,6) }
>>> dict_numbers
{1: 1, 2: 4, 3: 9, 4: 16, 5:25}

4. Merge dictionaries

There are many ways to merge dictionaries, we can use update () method, merge() operator, and even dictionary comprehensions.

But there is an easier way to merge dictionaries in Python, and that is by using the unpacking operator **​. We just need to add ** in front of each dictionary we wish to combine and use the extra dictionary to store the output.

dict_1 = {'a': 1, 'b': 2}
dict_2 = {'c': 3, 'd': 4}
merged_dict = {**dict_1, **dict_2}
>>> merged_dict
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

After we apply the ** operator to the dictionary, both will expand their contents and merge to create a new dictionary.

5. Remove duplicates in the list

Sometimes we need to make sure there are no duplicate values ​​in the list, although there is no one way to do it easily, we can use set to eliminate duplicates .

set is an unordered set in which each element is unique. This means that if we turn the list into a set, we can quickly remove duplicates. Then we just need to convert the set to a list again.

Let’s see a basic example to grasp it:

numbers = [1,1,1,2,2,3,4,5,6,7,7,8,9,9,9]

>>> list(set(numbers))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

6. Assigning values ​​to multiple variables in one line

Whenever we need to assign multiple variables, You can assign them in Python in one line instead of line by line (even variables from different types).

a, b, c = 1, "abc",True
>>> a
1
>>> b
'abc'
>>> c
True

It’s very concise, but it should be noted that the more variables we assign, the greater the chance of assigning them to wrong values. It’s a double-edged sword~

7. From Filtering values ​​in a list

Suppose we want to filter some values ​​from a list. There are many ways to do this, but one simple way is to use the filter() function.

This is the syntax of the filter function:

filter(function, iterable)

If we add a lambda function in the filter function, the effect will be better!

Let’s get a handle on it by filtering the even numbers from the list:

my_list = [10, 11, 12, 13, 14, 15]
>>> list(filter(lambda x: x%2 == 0, my_list ))
[10, 12, 14]

8. Sorting Dictionaries by Key

Sorting a dictionary is not as simple as sorting a list — —We cannot sort a dictionary using sort() or sorted() like we can with a list.

But we can combine dictionary deduction with the sorted() function to sort the dictionary by key.

In the example below, we will sort the dictionary by product name.

product_prices = {'Z': 9.99, 'Y': 9.99, 'X': 9.99}
>>{key:product_prices[key] for key in sorted(product_prices.keys())}
{'X': 9.99, 'Y': 9.99, 'Z': 9.99}

9. Sorting the dictionary by value

Similar to sorting the dictionary by key, we need to use the sorted() function and list comprehension to sort the dictionary by value, but we also need to add A lambda function.

First let's look at all the parameters of the sorted() function:

sorted(iterable, key=None, reverse=False)

To sort the dictionary by value, we need to use the key parameter. This parameter accepts a function that is used as the key for the sort comparison. Here we can use lambda functions to make things simpler.

Suppose we have a dictionary containing population values ​​and we want to sort it by value.

population = {'USA':329.5, 'Brazil': 212.6, 'UK': 67.2}

>>> sorted(population.items(), key=lambda x:x[1])
[('UK', 67.2), ('Brazil', 212.6), ('USA', 329.5)]

The only thing left now is to add dictionary derivation.

population = {'USA':329.5, 'Brazil': 212.6, 'UK': 67.2}

>>> {k:v for k, v in sorted(population.items(), key=lambda x:x[1])}
{'UK': 67.2, 'Brazil': 212.6, 'USA': 329.5}

Okay, that’s all I’ve shared today.

The above is the detailed content of Nine one-liners of Python code you should know and know. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete