python 示例_掌握python列表理解的11个示例

python 示例

List is a built-in data structure in Python and a collection of data points in square brackets. Lists can be used to store any data type or a mixture of different data types.

List是Python中的内置数据结构,在方括号中是数据点的集合。 列表可用于存储任何数据类型或不同数据类型的混合。

In this post, we will cover list comprehensions in python with 11 examples. I tried to order the examples according to their complexity levels (in my opinion).

在本文中,我们将用11个示例介绍python中的列表推导。 我尝试根据示例的复杂程度对示例进行排序(我认为)。

List comprehension is basically creating lists based on existing iterables. It can also be described as representing for and if loops with a simpler and more appealing syntax. List comprehensions are relatively faster than for loops.

列表理解基本上是基于现有可迭代对象创建列表。 它也可以描述为用更简单,更吸引人的语法表示for和if循环。 列表理解比for循环要快。

Image for post
Python list comprehension
Python列表理解

So we iterate over an iterable and do something (optional!) with the items and then put them in a list. In some cases, we just take the items that fit a specified condition.

因此,我们遍历一个可迭代的对象,并对这些对象做一些事情(可选!),然后将它们放在列表中。 在某些情况下,我们只取符合指定条件的物品。

Let’s start with the examples.

让我们从示例开始。

#example 1
import numpy as npa = [4,6,7,3,2]b = [x for x in a if x > 5]
b
[6, 7]

We iterate over a list (iterable) and take the elements that are greater than 5 (condition).

我们遍历一个列表(可迭代),并采用大于5的元素(条件)。

The equivalent for loop is:

for循环的等效项是:

b = []
for x in a:
if x > 5:
b.append(x)
b
[6, 7]

We can also do something with items before putting them in a new list:

我们还可以在将项目放入新列表之前对它们进行处理:

#example 2
import numpy as npa = [4,6,7,3,2]b = [x*2 for x in a if x > 5]
b
[12, 14]

We multiply the items that fit the condition by 2 and then put in a list.

我们将符合条件的项目乘以2,然后放入列表中。

The third example is a list of strings:

第三个示例是字符串列表:

#example 3
names = ['Ch','Dh','Eh','cb','Tb','Td']new_names = [name for name in names if name.lower().startswith('c')]new_names
['Ch', 'cb']

The condition is that string starts with the letter “c”. Since we have both capital and lowercase letters, we convert all letters to lowercase first.

条件是字符串以字母“ c”开头。 由于我们同时具有大写和小写字母,因此我们首先将所有字母都转换为小写。

The iterable does not have to be a list. It can be any python iterable. For instance, we can iterate over a 2-dimensional NumPy array which is actually a matrix.

可迭代的对象不必是列表。 它可以是任何可迭代的python。 例如,我们可以遍历实际上是矩阵的二维NumPy数组。

#example 4
import numpy as np
A = np.random.randint(10, size=(4,4))
A
array([[1, 7, 4, 4],
[5, 0, 0, 6],
[7, 5, 8, 4],
[1, 3, 2, 2]])max_element = [max(i) for i in A]
max_element
[7, 6, 8, 3]

We iterate over the rows in matrix A and take the maximum number.

我们遍历矩阵A中的行并取最大数。

Lists can store any data type. Let’s do an example with a list of lists.

列表可以存储任何数据类型。 让我们以一个列表列表为例。

#example 5
vals = [[1,2,3],[4,5,2],[3,2,6]]
vals_max = [max(x) for x in vals]
vals_max
[3, 5, 6]

We create a list of the maximum values in each list.

我们在每个列表中创建一个最大值列表。

We can have multiple conditions in a list comprehension.

我们在列表理解中可以有多个条件。

#example 6
names = ['Ch','Dh','Eh','cb','Tb','Td','Chb','Tdb']new_names = [name for name in names if
name.lower().endswith('b') and len(name) > 2]new_names
['Chb', 'Tdb']

We get the strings that end with the letter “b” and have a length greater than 2.

我们得到以字母“ b”结尾且长度大于2的字符串。

We can combine multiple conditions with other logical operators:

我们可以将多个条件与其他逻辑运算符结合起来:

#example 7
names = ['chb', 'ydb', 'thd', 'hgh']new_names = [name for name in names
if name.endswith('b') | name.startswith('c')]new_names
['chb', 'ydb']

We can also have nested list comprehensions which are a little bit more complex. They represent nested for loops.

我们还可以使用嵌套列表推导,这要复杂一些。 它们代表嵌套的for循环。

Consider the following list of lists:

请考虑以下列表列表:

vals = [[1,2,3],[4,5,2],[3,2,6]]

We want to take out each element from the nested lists so the desired output is:

我们想要从嵌套列表中取出每个元素,因此所需的输出为:

vals = [1,2,3,4,5,2,3,2,6]

Here is the nested list comprehension that does this operation:

这是执行此操作的嵌套列表理解:

#example 8
vals = [[1,2,3],[4,5,2],[3,2,6]]vals_exp = [y for x in vals for y in x]vals_exp
[1, 2, 3, 4, 5, 2, 3, 2, 6]

The syntax may not seem very intuitive. It will be clear when compared with the equivalent for loop.

语法似乎不太直观。 与等效的for循环相比,它会很明显。

Image for post
for loop vs list comprehension (Image by author)
for循环vs列表理解(作者提供的图片)

We put the blocks of a nested for loop into a list comprehension.

我们将嵌套的for循环的块放入列表推导中。

Note: There is a much easier way to do the operation in example 7 which is the explode function of pandas. I used list comprehension just to show the structure. It can be done with the explode function as follows:

注意 :在示例7中,有一种更简单的方法可以执行此操作,即熊猫的爆炸功能。 我使用列表理解只是为了显示结构。 可以使用explode函数完成此操作,如下所示:

pd.Series(vals).explode()

It returns a pandas series but you can easily convert it to a list.

它返回一个熊猫系列,但是您可以轻松地将其转换为列表。

We can also add conditions in nested list comprehensions. Consider the following list of lists with strings.

我们还可以在嵌套列表推导中添加条件。 考虑以下带有字符串的列表列表。

text = [['bar','foo','fooba'],['Rome','Madrid','Houston'], ['aa','bb','cc','dd']]

We only want the strings in nested lists whose length is greater than 3.

我们只希望嵌套列表中的字符串长度大于3。

#example 9
text_1 = [y for x in text if len(x)>3 for y in x]text_1
['aa', 'bb', 'cc', 'dd']

We put the condition on the nested lists, not on individual elements. Thus, the equivalent nested for/if loop syntax is as follows.

我们将条件放在嵌套列表上,而不是放在单个元素上。 因此,等效的嵌套for / if循环语法如下。

Image for post

We can also put a condition on individual elements.

我们还可以为单个元素设置条件。

#example 10
text_2 = [y for x in text for y in x if len(y)>4]text_2
['fooba', 'Madrid', 'Houston']

We now have strings that are longer than 4 characters. Since the condition is on individual elements, the equivalent nested for/if loops:

现在,我们有超过4个字符的字符串。 由于条件位于单个元素上,因此等效的嵌套for / if循环为:

Image for post

We may also need to put conditions on both nested lists and individual items.

我们可能还需要在嵌套列表和单个项目上都加条件。

#example 11
text_3 = [y.upper() for x in text if len(x) == 3 for y in x if y.startswith('f')]text_3
['FOO', 'FOOBA']

We get the items that start with the letter “f” in nested lists with a length of 3 and then convert all the letters of selected items to uppercase.

我们在嵌套列表中得到长度为3的以字母“ f”开头的项目,然后将所选项目的所有字母转换为大写。

The equivalent for/if loops:

等效的for / if循环:

Image for post

Tip: When you are not sure and cannot find out the syntax for list comprehension, try to build it with for/if loops. Then you can convert it to a list comprehension by adding individual blocks of loops into the list comprehension.

提示:如果不确定并且无法找到列表理解的语法,请尝试使用for / if循环进行构建。 然后,您可以通过将单个循环块添加到列表推导中,将其转换为列表推导。

奖励:什么时候不使用列表理解 (Bonus: When not to use list comprehension)

List comprehension loads the entire output list into memory. This is acceptable or even desirable for small or medium-sized lists because it makes the operation faster. However, when we are working with large lists (e.g. 1 billion elements), list comprehension should be avoided. It may cause your computer to crash due to the extreme amount of memory requirement.

列表理解将整个输出列表加载到内存中。 对于中小型列表,这是可以接受的,甚至是理想的,因为它使操作更快。 但是,当我们处理大型列表(例如10亿个元素)时,应避免理解列表。 由于极高的内存需求,可能会导致计算机崩溃。

A better alternative for such large lists is using a generator that does not actually create a large data structure in memory. A generator creates items when they are used. After the items are used, the generator throws them away. Using a generator, we can ask for the next item in an iterable until we reach the end and store a single value at a time.

对于这样的大列表,更好的选择是使用生成器 ,该生成器实际上不会在内存中创建大数据结构。 使用它们时,生成器会创建项目。 使用完这些物品后,生成器会将它们扔掉。 使用生成器,我们可以要求迭代器中的下一个项目,直到到达终点并一次存储一个值。

Thank you for reading. Please let me know if you have any feedback.

感谢您的阅读。 如果您有任何反馈意见,请告诉我。

翻译自: https://towardsdatascience.com/11-examples-to-master-python-list-comprehensions-33c681b56212

python 示例

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值