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

The nine special code skills!You can also write high-end Python code

編輯:Python

作者:韓信子@ShowMeAI
Python3 ◉ 技能提升系列:http://www.showmeai.tech/tutorials/56
本文地址:http://www.showmeai.tech/article-detail/303
聲明:版權所有,轉載請聯系平台與作者並注明出處
收藏ShowMeAI查看

Python It is an easy-to-use, readable and powerful programming language,It has some unique tricks and writing,Ours can be shortened considerably without compromising readability Python 代碼,Make it look more compact and advanced.

在本篇內容中ShowMeAI Summarize the most common ones for you『單行代碼(one-liner )』技巧,Make your code extra points even more『高級』!

Recommended for beginners to readShowMeAI的 圖解Python編程:從入門到精通系列教程 系列教程,Learn the full set Python 知識!

All the code below is available 在線 Python 編譯器 中運行,try it!

1.單行 if - else 語句

if-else 語句是我們在 Python One of the basic logical judgment grammars learned in . We usually write this statement as a branch,但 Python Actually support it if 和 else 語句在同一行,Simple and quick to complete the judgment.

如下為代碼示例:

age = 18
valid = "你是成年人"
invalid = "你是未成年人"
# 單行代碼
print(valid) if age >= 18 else print(invalid)

2.列表推導式

列表推導式是 Python Unique and very powerful syntax,It provides a short syntax to create a list from the values ​​of an existing list. More compact than functions and loops,You can even add conditional judgments.

The basic syntax of list comprehensions is as follows:

[expression for item in list]

Below is an example of a code application:

countries = ['united states', 'brazil', 'united kingdom', 'japan']
# List comprehensions with conditionals
capitalized = [country.title() for country in countries if country.startswith('u')]
print(capitalized)
['United States', 'United Kingdom']

List comprehensions are very concise,但是大家注意,Don't nest overly complex functions in list comprehensions,We still have to pay attention to keeping the code readable!

3.字典推導式

與列表推導式類似,Python There are also dictionary comprehensions in ,Dictionary comprehensions provide a short syntax,Create a dictionary in one line of code. 語法如下:

{
key: value for key, value in iterable}

下面是一個簡單的代碼示例:

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

4.合並詞典

We merge dictionaries if needed,有多種方法,可以使用 update()方法, merge()運算符,Including the dictionary comprehensions mentioned above.

一種非常簡單的方法,is by using the unpacking operator **,我們添加 **in front of each dictionary,Combined into a new dictionary to store the output.如下示例:

dict_1 = {
'a': 1, 'b': 2}
dict_2 = {
'c': 3, 'd': 4}
# 合並字典
merged_dict = {
**dict_1, **dict_2}
print(merged_dict)
{
'a': 1, 'b': 2, 'c': 3, 'd': 4}

5.Remove duplicate elements from a list

A very frequent process is to weigh list elements.The quickest way is to use it Python 中的集合set,A set is an unordered collection of elements. We just need to convert the list to a set and back to a list.

示例如下:

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

6.Single-line multi-variable assignment

If we need to assign values ​​to multiple variables,We can do this in one line,如下示例:

# Assign multiple variables on a single line
a, b, c = 1, "abc", True
print(a, b, c)
1 'abc' True

7.List element filtering

Another very common scenario is,Filter the list elements,Keeping elements that satisfy certain conditions results in a new list.There are many ways to implement this function,一個簡單的方法是使用 filter()函數.

基本語法如下:

filter(function, iterable)

我們甚至可以借助lambdaAnonymous function to define filter conditions,配合filter,The ability to quickly filter list elements in one line.For example, in the following example we filter out all even numbers in the list:

my_list = [10, 11, 12, 13, 14, 15]
# 選出所有偶數
print(list(filter(lambda x: x%2 == 0, my_list )))
[10, 12, 14]

8.字典排序:按照 key

For a little more complex structure,比如 Python 中的字典,If we want to rely onkey進行排序,沒辦法直接sort,但是我們可以借助sorted函數完成這個任務,For example, in the following example, we sort by the name of the product:

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

9.字典排序:按照 value

Sometimes we will need to base on the dictionaryvalue排序,This task can also be based onsorted()函數完成,Let's see all of them firstsorted()函數的參數,如下.

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

To follow the dictionaryvalue進行排序,我們需要使用 key 參數,This parameter accepts a function,The return value of the function is used as the basis for sorting. 這裡配合lambdaFunctions can easily accomplish tasks.

假設我們有一個包含人口值的字典,我們想按值對其進行排序.

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

We found that the returned result is a list,We can make use of the dictionary comprehension mentioned earlier,Treat it simply,如下:

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

參考資料

  • 在線 Python 編譯器 http://blog.showmeai.tech/python3-compiler/
  • 圖解Python編程:從入門到精通系列教程 http://www.showmeai.tech/tutorials/56


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