search
HomeBackend DevelopmentPython TutorialNine one-liners of Python code you should know and know


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
如何使用Python从列表中删除方括号如何使用Python从列表中删除方括号Sep 05, 2023 pm 07:05 PM

Python是一款非常有用的软件,可以根据需要用于许多不同的目的。Python可以用于Web开发、数据科学、机器学习等许多其他需要自动化处理的领域。它具有许多不同的功能,可以帮助我们执行这些任务。Python列表是Python的一个非常有用的功能之一。顾名思义,列表包含您希望存储的所有数据。它基本上是一组不同类型的信息。删除方括号的不同方法许多时候,用户会遇到列表项显示在方括号中的情况。在本文中,我们将详细介绍如何去掉这些括号,以便更好地查看您的列表。字符串和替换函数删除括号的最简单方法之一是在

制作 iPhone 上 iOS 17 提醒应用程序中的购物清单的方法制作 iPhone 上 iOS 17 提醒应用程序中的购物清单的方法Sep 21, 2023 pm 06:41 PM

如何在iOS17中的iPhone上制作GroceryList在“提醒事项”应用中创建GroceryList非常简单。你只需添加一个列表,然后用你的项目填充它。该应用程序会自动将您的商品分类,您甚至可以与您的伴侣或扁平伙伴合作,列出您需要从商店购买的东西。以下是执行此操作的完整步骤:步骤1:打开iCloud提醒事项听起来很奇怪,苹果表示您需要启用来自iCloud的提醒才能在iOS17上创建GroceryList。以下是它的步骤:前往iPhone上的“设置”应用,然后点击[您的姓名]。接下来,选择i

我们可以在Java列表中插入空值吗?我们可以在Java列表中插入空值吗?Aug 20, 2023 pm 07:01 PM

SolutionYes,Wecaninsertnullvaluestoalisteasilyusingitsadd()method.IncaseofListimplementationdoesnotsupportnullthenitwillthrowNullPointerException.Syntaxbooleanadd(Ee)将指定的元素追加到此列表的末尾。类型参数E −元素的运行时类型。参数e −要追加到此列表的元

Del和remove()在Python中的列表上有什么区别?Del和remove()在Python中的列表上有什么区别?Sep 12, 2023 pm 04:25 PM

在讨论差异之前,让我们先了解一下Python列表中的Del和Remove()是什么。Python列表中的Del关键字Python中的del关键字用于从List中删除一个或多个元素。我们还可以删除所有元素,即删除整个列表。示例使用del关键字从Python列表中删除元素#CreateaListmyList=["Toyota","Benz","Audi","Bentley"]print("List="

使用Python根据列表创建多个目录使用Python根据列表创建多个目录Sep 08, 2023 am 08:21 AM

Python凭借其简单性和多功能性,已成为各种应用程序中最流行的编程语言之一。无论您是经验丰富的开发人员还是刚刚开始编码之旅,Python都提供了广泛的功能和库,使复杂的任务变得易于管理。在本文中,我们将探讨一个实际场景,Python可以通过自动执行基于列表创建多个目录的过程来帮助我们。通过利用Python内置模块和技术的强大功能,我们可以有效地处理此任务,而无需手动干预。在本教程中,我们将深入研究创建多个目录的问题,并为您提供使用Python解决该问题的不同方法。在本文结束时,我们的目标是为您

如何使用 Vue 实现可折叠列表?如何使用 Vue 实现可折叠列表?Jun 25, 2023 am 08:45 AM

Vue是一款流行的JavaScript库,广泛应用于Web开发领域。在Vue中,我们可以很方便地实现各种组件和交互效果。其中,可折叠列表是一个比较实用的组件,它可以将列表数据分组,提高数据展示的可读性,同时又能够在需要展开具体内容时进行展开,方便用户查看详细信息。本文就将介绍如何使用Vue实现可折叠列表。准备工作在使用Vue实现可折叠列

在Java中从列表中随机选择项目在Java中从列表中随机选择项目Sep 06, 2023 pm 08:33 PM

List是JavaCollection接口的子接口。它是一种线性结构,按照顺序存储和访问每个元素。为了使用list的特性,我们使用实现了list接口的ArrayList和LinkedList类。在本文中,我们将创建一个ArrayList,并尝试随机选择该列表中的项目。在Java中随机选择列表中的项目的程序随机类别我们创建此类的对象来生成伪随机数。我们将自定义该对象并应用我们自己的逻辑从列表中选择任何随机项目。语法RandomnameOfObject=newRandom();Example1的翻译

使用while循环计算列表中数字的总和的Java程序使用while循环计算列表中数字的总和的Java程序Sep 13, 2023 pm 09:05 PM

介绍使用while循环计算列表中数字总和的Java程序是一个简单的程序,它获取整数列表并使用while循环结构计算它们的总和。在此程序中,创建了一个整数ArrayList,并将一些数字添加到该列表中。然后,程序使用while循环迭代列表中的每个元素,将每个元素添加到变量“sum”中,该变量跟踪数字的运行总和。循环完成后,“sum”的最终值将打印到控制台,它是列表中所有数字的总和。该程序演示了在编程中处理数据集合的常用技术,即使用循环迭代集合中的每个元素并对每个元素执行一些计算或转换。该计划还重点

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools