Python中的列表,集合,字典理解

Python的理解: (Comprehensions in Python:)

The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses.

理解包含一个表达式,后跟至少一个for子句和零个或多个forif子句。

There are three comprehensions in Python.

Python中包含三种理解。

Image for post
Types of comprehensions in Python(Image Source: Author)
Python的理解类型(图片来源:作者)

清单理解: (List Comprehensions:)

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable or to create a subsequence of those elements that satisfy a certain condition.

列表理解为创建列表提供了一种简洁的方法。 常见的应用是创建新列表,其中每个元素是应用于另一个序列的每个成员或可迭代的某些操作的结果,或者创建满足特定条件的那些元素的子序列。

Syntax:

句法:

[expression for item in iterable if conditional]

[expression for item in iterable if conditional]

The expression can be any arbitary expression, complex expressions, tuple, nested functions, or another list comprehension.

该表达式可以是任何任意表达式,复杂表达式,元组,嵌套函数或其他列表理解。

This is equivalent to

这相当于

for item in iterable:
if conditional:
expression

Return Type:

返回类型:

List

List

Using List Comprehension:

使用列表推导:

A list comprehension consists of brackets[] containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses that follow it.

列表推导由方括号[]组成,方括号[]包含一个表达式,后跟一个for子句,然后是零个或多个forif子句。 结果将是一个新列表,该列表是通过在表达式后面的forif子句的上下文中评估表达式而得出的。

Image for post
List Comprehension explained(Image Source: Author)
列表理解的解释(图片来源:作者)

1.列出理解与for循环。 (1. List comprehension vs for loop.)

By using List Comprehension, it is more concise and readable comparing to for loop.

通过使用List Comprehension,与for loop.相比,它更加简洁和可读for loop.

Finding square of numbers using List Comprehension vs for loop:

使用List Comprehension与for循环查找数字平方:

for loop vs List comprehension
for循环vs列表理解

2.列表理解与过滤器。 (2. List comprehension vs filter.)

过滤: (filter:)

Returns an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator

从那些为函数返回true的iterable元素返回一个迭代器。 iterable可以是序列,支持迭代的容器或迭代器

Finding Even Numbers Using List Comprehension vs filter():

使用列表理解vs filter()查找偶数:

List Comprehension vs filter()
列表理解与filter()

3.列出理解与地图 (3.List Comprehension vs map.)

map:

地图:

Return an iterator that applies a function to every item of iterable, yielding the results.

返回一个迭代器,该迭代器将函数应用于iterable的每个项目,并产生结果。

Finding square of numbers using List Comprehension vs map():

使用List Comprehension与map()查找数字平方:

List Comprehension vs map()
列表理解与map()

4.列表理解中的嵌套循环。 (4. Nested loops in List Comprehension.)

List comprehension can contain one or more for clause.

列表理解可以包含一个或多个for子句。

Example 1: Flatten a list using List Comprehension with two ‘for’ clause:

示例1 :使用带有两个'for'子句的List Comprehension展平一个列表:

Flatten a list using List comprehension
使用列表理解拼合列表

5.如果列表理解中有条件则为多个。 (5.Multiple if condition in List Comprehension.)

List comprehension can contain zero or more if clause.

列表推导可以包含零个或多个if子句。

Example: Finding numbers that are divisible by 2 and 3.

示例:查找可被2和3整除的数字。

List comprehension using two if clause
使用两个if子句进行列表理解

6.表达式可以是List Comprehension中的元组。 (6. The expression can be tuple in List Comprehension.)

We can mention expression as a tuple in a list comprehension. It should be written within parentheses. Otherwise, it will raise Error. The result will be a list of tuples.

我们可以在列表理解中将表达式称为元组。 它应该写在括号内。 否则,将引发错误。 结果将是一个元组列表。

Example 1: Creating a list of tuples using List Comprehension with two ‘for’ clause:

示例1 :使用带有两个'for'子句的List Comprehension创建元组列表:

List of tuples
元组列表

If the expression is a tuple and if not enclosed within parentheses, it will raise SyntaxError.

如果表达式是一个元组,并且如果未括在括号中,则它将引发SyntaxError。

The expression should be parenthesized if it is a tuple.
如果该表达式是元组,则应将其括起来。

Example 2:Using zip() function in List Comprehension:

示例2 :在列表理解中使用zip()函数:

zip() in List Comprehension
列表理解中的zip()

7.列表理解可用于在每个元素上调用方法。 (7. List comprehension can be used to call a method on each element.)

Example 1: Calling strip() method on each element in the list. It is used to strip the white spaces.

示例1:在列表中的每个元素上调用strip()方法。 它用于去除空白。

calling strip() method on each element
在每个元素上调用strip()方法

Example 2: Calling the upper() method on each element in the list.

示例2:在列表中的每个元素上调用upper()方法。

calling the upper() method on each element
在每个元素上调用upper()方法

8.列表理解可以包含复杂的表达式和嵌套函数。 (8. List comprehension can contain complex expressions and nested functions.)

Example 1:In the below example, in expression we are using the strip method and int function.

示例1:在下面的示例中,在表达式中,我们使用strip方法和int函数。

Example 2: In the below example, in expression, we are using abs() and str() function.

示例2:在下面的示例中,在表达式中,我们使用abs()和str()函数。

9.嵌套列表理解。 (9. Nested List Comprehension.)

The expression in a list comprehension can include another list comprehension also.

列表理解中的表达式也可以包括另一个列表理解。

Example: First List comprehension given as expression will return a list of even numbers from 0 to 10. Nested list comprehension will return that expression (list of even numbers from 0 to 10) three times(range(3)).

示例:以表达式形式给出的第一列表理解将返回一个从0到10的偶数列表。嵌套列表理解将返回该表达式(从0到10的偶数列表)三次(range(3))。

Nested List Comprehension
嵌套列表理解

集合理解: (Set Comprehensions:)

Like List comprehension, Python supports Set Comprehension also.Set comprehension is written within curly braces{}.Returns new set based on existing iterables.

像List理解一样,Python也支持SetComprehension。Set理解被写在花括号{} 。根据现有的可迭代对象返回新的set。

Return Type: Set

返回类型: Set

Syntax:

句法:

{expression for item in iterable if conditional}

How to find even numbers using set Comprehension:

如何使用Set Comprehension查找偶数:

even no using set comprehension
甚至不使用集合理解

How to find the square of numbers using Set Comprehension.

如何使用Set Comprehension查找数字的平方。

Square of numbers using set comprehension
使用集合理解的数字平方

If condition in Set comprehension:

如果设置理解中的条件:

Below example, we are calculating the square of even numbers.The expression can be a tuple, written within parentheses. We are using if condition to filter the even numbers.Sets are unordered. So elements are returned in any order.

在下面的示例中,我们正在计算偶数的平方。表达式可以是一个用括号括起来的元组。 我们使用if条件过滤偶数,集合是无序的。 因此,元素以任何顺序返回。

字典理解: (Dictionary Comprehension:)

Like List and Set comprehension, Python supports Dictionary Comprehension.

像List和Set理解一样,Python支持Dictionary Comprehension。

A dict comprehension, in contrast, to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.

相反,dict理解要列出和设置理解,则需要两个表达式之间用冒号分隔,后跟通常的“ for”和“ if”子句。 运行理解时,将生成的键和值元素按生成顺序插入新字典中。

Dictionary comprehension is written within curly braces{}.In Expression key and value are separated by :

字典理解写在大括号{} 。在Expression中,键和值由:字符分隔:

Syntax

句法

{key:value for (key,value) in iterable if conditional}

Return Type: dict

返回类型: dict

How to find the square of numbers using Dictionary Comprehension.

如何使用Dictionary Comprehension查找数字的平方。

square of numbers using dict comprehension
使用dict理解的数字平方

How to iterate through two dictionaries using dictionary comprehension:

如何使用字典理解迭代两个字典

Iterate through two dictionaries using dict comprehension
使用dict理解迭代两个字典

If Condition in Dictionary Comprehension:

如果字典理解中的条件:

Zero or more if clause can be used in dictionary comprehension.In the below example, we are calculating the square of even numbers.

字典理解中可以使用零个或多个if子句。在下面的示例中,我们计算偶数的平方。

Finding the number of occurrences using dictionary comprehension:

使用字典理解来查找出现次数:

In the below example, we are calculating the number of occurrences of each character in a string. We can call the method count() on each element in the string. count() will return the number of occurrences of a substring in the string.

在下面的示例中,我们正在计算字符串中每个字符的出现次数。 我们可以在字符串的每个元素上调用方法count()count()将返回字符串中子字符串出现的次数。

We are calculating the number of occurrences of each word in the list by calling count()on each word in the list.

我们通过调用列表中每个单词的count()count()列表中每个单词的出现count()

finding the number of occurrences
查找出现次数

生成器表达式: (Generator Expression:)

A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces.

生成器表达式产生一个新的生成器对象。 它的语法与理解相同,只是用括号而不是括号或花括号括起来。

Generator Expression is written within ().It yields a generator. The generator is a function that returns an object (iterator) which we can iterate over (one value at a time). The performance improvement from the use of generators is the result of the lazy (on-demand) generation of values, which translates to lower memory usage.

生成器表达式写在()它产生一个生成器。 生成器是一个返回对象(迭代器)的函数,我们可以对其进行迭代(一次一个值)。 使用生成器可以提高性能,这是由于值的延迟(按需)生成的结果,这转化为较低的内存使用量。

Return Type: Generator object

返回类型: Generator对象

generator expression
生成器表达式

结论: (Conclusion:)

  • Return Type

    返回类型

    List Comprehension-

    清单理解-

    List

    清单

    Set Comprehension-

    设定理解-

    Set

    Dictionary Comprehension —

    字典理解—

    dict

    字典

    Generator Expression-

    生成器表达式

    Generator Object

    生成器对象

  • Tuple comprehension is not supported. A generator expression is written within ().Its syntax is the same as List Comprehension. It returns a generator object.

    不支持元组理解。 生成器表达式被编写 ()其语法与列表理解相同。 它返回一个生成器对象。

  • List comprehension is written within []

    列表理解写在[]

    Set comprehension is written within

    集合理解写在

    {}

    {}

    Dictionary comprehension is written within

    字典理解写在

    {}

    {}

  • A dict comprehension, in contrast, to list and set comprehensions, needs two expressions separated with a colon.

    相反,字典理解要列出和设置理解,则需要两个用冒号分隔的表达式。
  • The expression can also be tuple in List comprehension and Set comprehension. If an expression is tuple, it should be written within ().

    该表达式也可以是List理解和Set理解中的元组。 如果表达式是元组,则应将其写在().

翻译自: https://medium.com/analytics-vidhya/list-set-dictionary-comprehensions-in-python-8a0a7c06115e

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值