设置字典值为列表_使用列表字典和设置理解力来缩短代码

设置字典值为列表

While using Python for almost a year now I have regularly come across the word ‘comprehensions’ without necessarily understanding what exactly it meant or what it covered. It is only recently that I discovered that I had readily been using them in my code to generate lists and that I had not fully comprehended their ability to be able to shorten my code from multiple lines into one single one. Also, this code shortening method could be used not just in lists, but also for dictionaries and sets as well. This article is, therefore, my attempt to explain their applicability to lists, dictionaries and sets and how they could reduce the amount of code you need in everyday programming.

在使用Python近一年的时间里,我经常遇到“理解”一词,而不必理解它的确切含义或涵盖的范围。 直到最近,我才发现自己已经在代码中轻松使用它们来生成列表,并且我还没有完全理解它们能够将我的代码从多行缩短为一行的能力。 另外,这种代码缩短方法不仅可以用于列表中,还可以用于字典和集合。 因此,本文旨在解释它们对列表,字典和集合的适用性,以及它们如何减少日常编程中所需的代码量。

Firstly, Comprehensions are pieces of code that can be used in a single line to create lists, dictionaries and sets. This is instead of having to use multiple lines for for-loop and it also reduces the need to use map(), filter() and reduce() functions. They consist of brackets (square or curly according to the data type you want to create) that contain an expression, followed by a for clause and potentially one or more if-clauses. The expression itself can be anything, meaning that you can put many different objects in lists, as long as they are iterable. Hence, it is worth exploring the effects that these may have on your code in terms of reducing the number of lines used and increasing the readability.

首先,理解是可以在一行中使用的代码片段,以创建列表,字典和集合。 这样就不必为循环使用多行代码,而且还减少了使用map(),filter()和reduce()函数的需要。 它们由包含表达式的方括号(根据您要创建的数据类型,用方括号或大括号)组成,后跟一个for子句以及可能的一个或多个if子句。 表达式本身可以是任何东西,这意味着您可以将许多不同的对象放入列表中,只要它们是可迭代的即可。 因此,就减少使用的行数和提高可读性而言,值得探讨它们可能对您的代码产生的影响。

清单 (Lists)

lists can simply be created in python by placing items inside square brackets ([]) separated by commas as follows.

列表可以简单地在python中创建,方法是将项目放在方括号([])内,并用逗号分隔,如下所示。

list1 = [1, 2, 3, "hello", 7.0, 52]

These are commonly used in programming for multiple purposes but can be cumbersome to either write out in long-form or to edit using for loops. Firstly, in terms of creating lists, small lists may be easy enough to type out in long-form, such as:

这些通常用于多种目的的编程中,但是以长格式写出来或使用for循环进行编辑可能会很麻烦。 首先,就创建列表而言,小列表可能很容易以长格式键入,例如:

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

but they can become unwieldy when this becomes much longer i.e. in the range of 0–50 or even longer. They can be created easily enough through a for loop using the range function as follows:

但是当它们变得更长时,例如在0到50甚至更长的范围内,它们可能变得笨拙。 通过使用范围函数的for循环,可以很容易地创建它们,如下所示:

nums = []for i in range(1, 51):
nums.append(i)print(nums)# out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

but we can use list comprehensions to shorten this to a single line and remove the need for the append() method.

但是我们可以使用列表推导将其缩短为一行,并不需要使用append()方法。

nums = [i for i in range(1,51)]print(nums)# out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

Essentially the for loop is placed in a single line and the list is initialised at the same time, removed the need for both the first and second lines of code from the example produced above.

本质上,for循环放在一行中,并且列表在同一时间初始化,从上面产生的示例中消除了对第一行和第二行代码的需要。

This becomes more important when we start to add conditions to the numbers added to the list such as only allowing even numbers and wanting these to be squared. Again, this can be produced using a for loop as follows:

当我们开始向添加到列表中的数字添加条件时,例如仅允许偶数并希望对它们求平方,这变得尤为重要。 同样,可以使用for循环来生成此代码,如下所示:

square_nums = []for x in range(1,26):
if x % 2 == 0:
square_nums.append(x**2)print(square_nums)# out: [4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576]

But again this can be shortened to a single line using list comprehensions, reducing the need for the lines used to loop over the range, create a conditional and append the result to the original list.

但是同样可以使用列表理解将其缩短为一行,从而减少了用于循环遍历范围,创建条件并将结果附加到原始列表的行的需求。

square_nums = [x**2 for x in range(1,26) if x % 2 == 0]print(square_nums)#out: [4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576]

Here, the transformation of the numbers is performed at the beginning of the line as x**2, the for loop is performed in the middle of the line as for x in range(1,26), and the conditional is performed at the end as if x % 2 == 0. This essentially makes the code much more readable as all the actions are performed in a single line, and reduces the amount of code that is required to produce the same output.

这里,数字的转换在行的开头以x**2的形式执行,for循环在行的中间for x in range(1,26)的形式执行,有条件的在就像if x % 2 == 0 。 从本质上讲,这使代码更具可读性,因为所有操作都在一行中执行,并且减少了产生相同输出所需的代码量。

This can also reduce the need for the append(), map(), filter() or reduce() methods to act on existing lists in the creation of new ones, again reducing the complexity of the code and making it more readable.

这还可以减少在创建新列表时对append(),map(),filter()或reduce()方法作用于现有列表的需求,从而再次降低了代码的复杂性并使代码更具可读性。

Similar examples are readily available and more information can be easily obtained through other articles on a medium such as here and here. However, it is worth noting that these comprehensions can also be used on both dictionaries and sets.

类似的示例很容易获得,并且可以通过诸如此处此处的媒体上的其他文章轻松获得更多信息。 但是,值得注意的是,这些理解也可以在字典和集合上使用。

辞典 (Dictionaries)

A dictionary is an unordered collection of data that is changeable and indexed, written using curly braces using key and value pairs. Here, the keys are used to be able to access the values and are used often to store information for which having such pairs is useful. An example of this is provided below, such as being used to store grades.

字典是可更改和索引的无序数据集合,使用大括号使用键和值对编写。 在这里,键用于访问值,并且经常用于存储具有这种对的信息。 下面提供了一个示例,例如用于存储成绩。

Grades = {
"Steven": 57,
"Jessica": 82,
"William": 42,
"Hussein": 78,
"Mary": 65,
}print(Grades)# out: {'Steven': 57, 'Jessica': 82, 'William': 42, 'Hussein': 78, 'Mary': 65}

Similarly to lists, these can sometimes be time-consuming to hard-code from the base and as such can be constructed using for loops and conditionals, but can more simply be constructed using comprehensions. For example, say for the list we created above that we not only wanted to know the square of the number, but we wanted to store the original number as well such that we can use this to easily look up its squared value. Then, we can simply create a dictionary with key-value pairs where the key represents the original number, and the value represents that number squared. Using a for loop:

与列表类似,从列表中进行硬编码有时会很耗时,因此可以使用for循环和条件构造它们,但是可以使用理解来更简单地构造它们。 例如,对于上面创建的列表,我们不仅要知道数字的平方,还想存储原始数字,以便我们可以使用它轻松地查找其平方值。 然后,我们可以简单地创建一个包含键值对的字典,其中键代表原始数字,值代表那个平方的数字。 使用for循环:

#initialising empty dict
even_squared_dict = {}for x in range(1,10):
if x % 2 == 0:
even_squared_dict[x] = x**2print(even_squared_dict)# out: {2: 4, 4: 16, 6: 36, 8: 64}

But using a dictionary comprehension:

但是使用字典理解:

even_sqaured_dict = {x: x**2 for x in range(1,10) if x % 2 ==0}print(even_squared_dict)# out: {2: 4, 4: 16, 6: 36, 8: 64}

Essentially, the only difference between this and the list comprehension is the use of curly braces to contain the comprehension and the placement of x before the colon to indicate that this represents the key.

从本质上讲,此理解与列表理解之间的唯一区别是使用花括号来包含理解和将x放在冒号之前,以表明这表示键。

This can be then also be used to create a dictionary based on an already existing list. For example below, a dictionary comprehension is used to create a dictionary with a key of the three-digit country codes and the value as the two-digit country code where the two-digit code is the same as the first two digits of the three-digit code.

然后,也可以将其用于基于现有列表创建字典。 例如,在下面的示例中,使用字典理解来创建一个字典,该字典的键为三位数的国家/地区代码,其值为两位数的国家/地区代码,其中两位数字的代码与三位的前两位数字相同位数字的代码。

ThreeCharCodes = ["CAN", "FIN", "FRA", "GAB", "HKG", "IMN",
"MCO", "NPL"]cntryDict = {c: c[:2] for c in threeCharCodes}print(cntryDict)# out: {'CAN': 'CA', 'FIN': 'FI', 'FRA': 'FR', 'GAB': 'GA', 'HKG': 'HK', 'IMN': 'IM', 'MCO': 'MC', 'NPL': 'NP'}

套装 (Sets)

Finally, comprehensions can also be used in the creation of sets, which are a datatype that unlike lists or tuples, cannot store multiple occurrences of the same element. In doing so it stores unordered values, initialised by passing a list into set() or by using curly braces to contain the values separated by a comma (although empty curly braces would initialise a dictionary). An example of this is provided below:

最后,还可以将理解用于集合的创建中,集合是一种数据类型,与列表或元组不同,它不能存储同一元素的多次出现。 这样,它存储无序值,方法是通过将列表传递到set()或使用花括号将其包含以逗号分隔的值进行初始化(尽管空花括号将初始化字典)。 下面提供了一个示例:

Fruits1 = set(["apple", "banana", "cherry", "apple"])
print(Fruits1)Fruits2 = {"orange", "pear", "grape", "pear"}
print(Fruits2)# out: {'apple', 'cherry', 'banana'}
{'grape', 'pear', 'orange'}

It can be seen here clearly that although multiple values of apple or pear were passed to the set, only one instance was produced. Again, these can be produced using a for loop as below:

在这里可以清楚地看到,尽管将多个值的applepear传递给该集合,但仅生成了一个实例。 同样,可以使用如下所示的for循环来生成这些:

import randomnums = set([])for x in range(25):
y = random.randint(10,20)
nums.add(y)print(nums)# out: {10, 12, 14, 15, 16, 17, 18, 20}

Where although 25 random integers in the range of 10–20, the final output contained only 8 unique values, instead of the 25 values that have appeared in a list. Again, this can be more succinctly written using a comprehension for a set.

尽管25个随机整数在10–20范围内,但最终输出仅包含8个唯一值,而不是列表中出现的25个值。 同样,可以使用对集合的理解来更简洁地编写这些内容。

nums = {random.randint(10,20) for num in range(25)}print(nums)# out: {11, 12, 13, 14, 15, 16, 17, 19, 20}

The difference between this and a list comprehension therefore is the use of curly braces, rather than square brackets in containing the comprehension.

因此,此列表理解与列表理解之间的区别在于使用大括号而不是包含方括号的方括号。

Similarly to both list and dictionary comprehensions, this can also be used on an existing list to generate a set. For example, if we wanted to change kilometres into miles based on a division by 1.6, only requiring unique values and restricting this to values that are less than 100 kilometres.

与列表和字典理解相似,这也可以用于现有列表以生成集合。 例如,如果我们想将公里数除以1.6,则仅需要唯一值并将其限制为小于100公里的值。

kms = [10, 12, 65, 40, 12, 75, 34, 65, 10, 10, 38, 100, 160, 200]miles = {d/1.6 for d in kms if d < 100}print(miles)# out: {0.625, 0.75, 2.5, 2.125, 4.0625, 4.6875, 2.375}

摘要 (Summary)

Comprehensions can therefore easily be applied for the purpose of creating new lists, dictionaries and sets. Using these allows you to reduce the number of lines required to produce them and increases readability. They can be used as replacements for the append(), map(), filter() or reduce() functions.

因此,可以很容易地将理解应用于创建新列表,字典和集合的目的。 使用这些可以减少生产它们所需的行数并提高可读性。 它们可以用作append(),map(),filter()或reduce()函数的替代品。

These can obviously be scaled up to perform more complex comprehensions such as using lambda functions, nested list comprehensions or multiple conditionals. However, in doing so it is worth noting that comprehensions can quite quickly become unwieldy and difficult to comprehend, in which case it would be worth reverting back to the creation of functions or for loops in order for improved readability when several operations need to be performed.

这些显然可以扩展以执行更复杂的理解,例如使用lambda函数,嵌套列表理解或多个条件。 但是,这样做时值得注意的是,理解很快就会变得笨拙且难以理解,在这种情况下,当需要执行多个操作时,有必要回到创建函数或循环的目的,以提高可读性。 。

翻译自: https://towardsdatascience.com/the-use-of-list-dictionary-and-set-comprehensions-to-shorten-your-code-66e6dfeaae13

设置字典值为列表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值