列表创建字典

    科技2022-07-12  129

    列表创建字典

    那一件事 (That One Thing)

    You know that road-trip game, where you only count cars you see if they are of the same color. On a long, lonely stretch of road, it is a game of anticipation. On a busy highway, it can get a bit neurotic. Sometimes, the game can morph into one of comparing how many different colored cars you can count. Without some sort of tally sheet, keeping count in this way quickly can get out of hand. Even if you make a list comprising each observation, counting them up for each category can be a bit of a hassle.

    您知道公路旅行游戏,您只在其中计算汽车的颜色是否相同。 在漫长而孤独的道路上,这是一场期待的游戏。 在繁忙的高速公路上,它可能会变得有些神经质。 有时候,游戏可以变成比较您可以计算多少种不同颜色的汽车之一。 没有某种理赔表,以这种方式快速计数可能会失控。 即使您列出了包含每个观察值的列表,也要为每个类别累加计数可能会有些麻烦。

    A digital list can be just trying. You may be able to highlight or sort a spreadsheet list, to make counting a little easier, or perhaps you could aggregate fields in a SQL database. In Python, you also have a few options for managing such a task.

    可以尝试使用数字清单。 您可能可以突出显示或对电子表格列表进行排序,以使计数更加容易,或者您可以聚合SQL数据库中的字段。 在Python中,您还有一些管理此类任务的选项。

    In this article, will review the following:

    在本文中,将回顾以下内容:

    Understanding the Python list

    了解Python清单 What is a dictionary, in Python?

    在Python中,什么是字典? Converting list elements into dictionary keys

    将列表元素转换成字典键 How you can count item occurrences in a list, by converting the list to a dictionary

    如何通过将列表转换为字典来计算列表中项目的出现次数 Code for implementation in Python

    在Python中实现的代码

    Python中的清单 (Lists in Python)

    In Python, a list can be any sequence of values. We indicate a list by enclosing the values in square brackets and separating them with commas. Lists may contain numbers, text strings, or any type of object (or a mixture of objects).

    在Python中,列表可以是任何值序列。 我们通过将值括在方括号中并用逗号分隔来指示列表。 列表可以包含数字,文本字符串或任何类型的对象(或对象的混合物)。

    A Python list of integers from 1–5 looks like this:

    1-5的Python整数列表如下所示:

    # spaces after the commas are not required[1, 2, 3, 4, 5]

    Strings in a list are surrounded by quotes:

    列表中的字符串用引号引起来:

    # a four-item combination of strings and numbers["cat",3,1,"dog"]

    Lists can even contain other lists:

    列表甚至可以包含其他列表:

    # a four-item list of two lists, a number and a string[[1, 2, 3, 4, 5], 541, ["cat",3,1,"dog"], "Chuck"]# and, of course, we can assign a variable to our listmy_mixed_list = [[1, 2, 3, 4, 5], 541, ["cat",3,1,"dog"], "Chuck"]

    Python lists are mutable. This means you can change them. You can perform math on list items, change their order, or append new items to the list. In fact, the actions that may be performed on lists amounts to — well — a very long list. Let’s see what a couple of these operations look like.

    Python列表是可变的。 这意味着您可以更改它们。 您可以对列表项执行数学运算,更改其顺序或将新项追加到列表。 实际上,可以对列表执行的操作相当长。 让我们看看其中的几个操作是什么样的。

    操作一: (Operation 1:)

    # multiplying a list to extend the listmy_list = [1, 2, 3, 4, 5]result = my_list * 2print(result)> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

    The above operation results in a list that is twice as long, with each item reoccurring in its original order. We can verify the lengths or number of items in our lists with Python’s len() list method:

    上面的操作导致列表的长度是原来的两倍,并且每个项目都以其原始顺序重复出现。 我们可以使用Python的len() list方法来验证列表中项目的长度或数量:

    # printing the length of `my_list`print("The length of my_list is ", len(my_list))> The length of my_list is 5# printing the length of `result`print("The length of result is ", len(result))> The length of result is 10

    操作2: (Operation 2:)

    # multiplying list itemsmy_list = [1, 2, 3, 4, 5]# creating a new list by multiplying each `mylist` item (i) by tworesult2 = [i*2 for i in my_list]print(result2)> [2, 4, 6, 8, 10]

    This second operation results in a list (result2) that is the same length as our original (my_list), but each number is multiplied by two.

    第二个操作产生一个列表( result2 ),该列表的长度与原始列表( my_list )的长度相同,但是每个数字都乘以2。

    Note: We used len() to find the number of items, in our lists. In addition, we can use Python’s built-in range method to find start-and-stop indexes:

    注意 : 我们使用 len() 在列表中查找项目数。 另外,我们可以使用Python的内置 range 方法来查找起止索引 :

    print(range(len(my_list)))> range(0, 5)print(range(len(result)))> range(0, 10)

    Python indexing begins at zero. The range for my_list starts at index 0 — the value for which is 1 in my_list — and goes up to (but does not include) index 5.

    Python索引从零开始。 my_list的范围从索引0开始-在my_list其值为1-一直到(但不包括)索引5。

    We will use range() in the code for our main task. The task is to count how many times each item occurs on our list. For example: on the five-item list [“dog”, “cat”, “dog”, “cat”, “mouse”], “dog” and “cat” each occur twice, and “mouse” occurs once. To accomplish our task in Python, we will need to identify every unique item in the list and account for any duplicates. Our method for this task will involve using a Python dictionary.

    我们将在代码中使用range()作为主要任务。 任务是计算每个项目出现在我们列表中的次数。 例如:在五项列表中[“dog”, “cat”, “dog”, “cat”, “mouse”] ,“ dog”和“ cat”分别出现两次,而“ mouse”出现一次。 为了完成我们在Python中的任务,我们将需要识别列表中的每个唯一项并说明所有重复项。 我们用于此任务的方法将涉及使用Python字典。

    Photo by Pisit Heng on Unsplash Pisit Heng在 Unsplash上 拍摄的照片

    (Python)字典 ((Python) dictionaries)

    A Python dictionary is a collection of data values, stored as key-value pairs. For the print dictionary pictured above, if each word were thought of as a key, then it’s definition might be its value (in a simple analogy).

    Python字典是存储为键值对的数据值的集合。 对于上图所示的印刷词典,如果每个单词都被认为是一个关键字,那么它的定义可能就是它的值(简单地类推)。

    Python dictionaries are written with curly braces. Below is an example of a dictionary with two entries:

    Python字典用大括号编写。 下面是带有两个条目的字典的示例:

    # a dictionary of student heights in feet and inchesstudent_height = {"Johnette K.":"5'7", "Carl D.":"5'11"}

    Notice that each key, here indicating a student’s first name and last initial, is followed by a colon. Each key’s matching value follows the colon. In the above example, the matching value for the key, “Carl D.”, is “5'11”. Dictionary keys are unique and immutable — there can only be one “Carl D.”; however, as with lists, dictionary values can reference any type of object, including lists, other dictionaries, or even databases (but, let’s not get ahead of ourselves).

    请注意,每个键(在此表示学生的名字和姓氏的首字母)后跟一个冒号。 每个键的匹配值都以冒号结尾。 在上面的示例中,键“ Carl D.”的匹配值是“ 5'11”。 字典键是唯一且不可变的-只能有一个“ Carl D.”; 但是,与列表一样,字典值可以引用任何类型的对象,包括列表,其他字典甚至数据库(但是,让我们不要超越自己)。

    So, how does a dictionary help us with our task?

    那么,词典如何帮助我们完成任务呢?

    将列表转换成字典 (Converting a list to a dictionary)

    Since dictionary keys are unique and immutable, if we convert list items to dictionary keys we will have a key for each unique item in our list. Converting the elements in our ten-item result list to dictionary keys would produce a dictionary with five unique keys:

    由于字典键是唯一且不可变的,因此如果将列表项转换为字典键,我们将为列表中的每个唯一项都有一个键。 将十项result列表中的元素转换为字典键,将产生一个具有五个唯一键的字典:

    # multiplying a list to extend the listmy_list = [1, 2, 3, 4, 5]result = my_list * 2print(result)> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]# creating an empty dictionaryconverted_dict = {}# updating `converted_dict` with keys for each element (i) in `result`for i in result: converted_dict.update({i:""})print(converted_dict)> {1: '', 2: '', 3: '', 4: '', 5: ''}

    Note: We use the ‘update’ dictionary method to add or change key-value pairs (similar to how we used append() to add to a list). We created an empty string value (“”), for each key. We could also have updated None as the value for each key.

    注意:我们使用'update'字典方法添加或更改键值对(类似于我们使用 append() 添加到列表的方式)。 我们为每个键创建了一个空字符串值(“”)。 我们还可以将 None 更新 为每个键的值。

    Wait!

    等待!

    Doesn’t this just put us back where we started?

    这不只是让我们回到了起点吗?

    Admittedly, our dictionary looks a lot like our list, with a colon and an empty string added to each item. However, key-value pairs enable us to use each value to represent the count of the number of occurrences for each item (each key). For the result list, since each item occurs twice, our final dictionary would end up as follows: {1:‘2’, 2:‘2’, 3:‘2’, 4:‘2’, 5:‘2’}

    不可否认,我们的字典看起来很像我们的列表,在每个项目中都添加了一个冒号和一个空字符串。 但是,键值对使我们能够使用每个值来表示每个项目(每个键)的出现次数计数。 对于result列表,由于每个项目出现两次,因此我们的最终字典将如下所示: {1:'2', 2:'2', 3:'2', 4:'2', 5:'2'}

    较长的清单 (Longer Lists)

    Now we can get on with the one thing we set out to accomplish.

    现在,我们可以着手完成我们要完成的一件事。

    Our solution for counting item occurrences in a Python list presumes some basic familiarity with for loops. We already sneaked for loops into Operation 2 (in our list comprehension, [i*2 for i in my_list]). The loop could also be written as follows:

    我们计算Python列表中项目出现次数的解决方案假定对for循环有一些基本的了解。 我们已经潜入了操作2的循环(在我们的列表理解中 , [i*2 for i in my_list] list中 [i*2 for i in my_list] )。 该循环也可以编写如下:

    # multiplying list itemsmy_list = [1, 2, 3, 4, 5]# instatiating `result2` as an empty listresult3 = []# the for loop...# double each element and append it to a new `result3` listfor i in my_list: result3.append(i*2)print(result3)> [2, 4, 6, 8, 10]

    The expanded for loop mirrors our earlier use when we updated converted_dict (“for i in result:…”).

    扩展的for循环反映了我们在更新converted_dict (“ for i in result: …”)时的用法。

    In Python, you can expect to encounter lists in which items repeat. In practice, these might involve:

    在Python中,您可能会遇到重复项的列表。 实际上,这些可能涉及:

    college majors, based on a campus survey,

    大学专业,根据校园调查, homes by price range,

    价格范围内的房屋, or, say, car colors.

    或汽车颜色。

    We have practiced with lists that have only a few items, but what if we want to count the number of occurrences for each item in a list that looks more like this?:

    我们练习了只有几个项目的列表,但是如果我们想计算看起来更像这样的列表中每个项目的出现次数怎么办?:

    color_list = ['light blue', 'gold', 'silver', 'blue', 'gold', 'green', 'blue', 'green', 'light blue', 'black', 'gold', 'red', 'light blue', 'light blue', 'silver', 'silver', 'black', 'silver', 'black', 'silver', 'gold', 'green', 'green', 'black', 'silver', 'red', 'black', 'black', 'gold', 'light blue', 'gold', 'black', 'silver', 'black', 'black', 'green', 'light blue', 'green', 'red', 'red', 'green', 'black', 'blue', 'red', 'gold', 'light blue', 'red', 'light blue', 'blue', 'blue', 'blue', 'green', 'red', 'silver', 'blue', 'blue', 'green', 'silver', 'blue', 'green', 'gold', 'blue', 'silver', 'red', 'light blue', 'red', 'gold', 'red', 'gold', 'light blue']

    Well, that is precisely what we shall do, next.

    好吧,这就是我们下一步要做的。

    Photo by David Clode on Unsplash David Clode在 Unsplash上 拍摄的照片

    用Python实现 (Implementation in Python)

    Let’s start this example from the beginning.

    让我们从头开始这个例子。

    步骤1:导入所需的模块。 (Step 1: Import the required module.)

    # importing Python's `random` moduleimport random# we will also set a random seed for reproducibilityrandom.seed(7)

    第2步:导入数据。 (Step 2: Bring in data.)

    We will instantiate a list of 7 colors. If you already have a list you wish to use, you can skip steps 2–4, in which we create the relatively short, initial list and then randomly append elements from the list to a new, longer list.

    我们将实例化7种颜色的列表。 如果您已经有了要使用的列表,则可以跳过步骤2–4,在该步骤中,我们创建相对较短的初始列表,然后将列表中的元素随机追加到新的较长列表中。

    # instantiating an alphabetized list of 7 car colorsshort_list = ['black', 'blue', 'gold', 'green', 'light blue', 'red', 'silver']

    步骤3:以编程方式创建扩展的随机列表。 (Step 3: Programmatically create an extended, randomized list.)

    # choosing a random item from `short_list`, seventy times,# to create a longer `extended_list`, using # the `random` module’s `.choices()` methodextended_list = random.choices(short_list, k=70)print (extended_list)> ['gold', 'blue', 'light blue', 'black', 'green', 'gold', 'black', 'green', 'black', 'green', 'black', 'black', 'gold', 'red', 'black', 'blue', 'light blue', 'silver', 'light blue', 'gold', 'silver', 'black', 'silver', 'gold', 'blue', 'black', 'gold', 'red', 'blue', 'light blue', 'light blue', 'gold', 'green', 'black', 'black', 'blue', 'light blue', 'gold', 'gold', 'light blue', 'green', 'gold', 'red', 'light blue', 'blue', 'light blue', 'green', 'silver', 'red', 'gold', 'silver', 'black', 'gold', 'red', 'blue', 'green', 'black', 'light blue', 'red', 'light blue', 'silver', 'gold', 'light blue', 'light blue', 'light blue', 'green', 'red', 'silver', 'green', 'light blue']

    Notice that items are no longer in their original order. Items are added to extended_list until we reach seventy items (k=70). Now, it is not so easy to count the number of occurrences of each color on the list.

    请注意,项目不再按其原始顺序排列。 将项目添加到extended_list直到达到七十个项目(k = 70)。 现在,要计算列表上每种颜色的出现次数并不容易。

    步骤4:实例化字典。 (Step 4: Instantiate a dictionary.)

    # creating an empty dictionary for our colorscolors_dict = {}

    第5步:将颜色添加到字典中。 (Step 5: Add our colors to a dictionary.)

    Here, we accomplish several subtasks in a single line of code:

    在这里,我们在一行代码中完成了几个子任务:

    We find the length of the list, with Python’s len() method.

    我们使用Python的len()方法找到列表的长度。

    We use the built-in range() function to get the index for each of the len() items on the list (Recall that Python numbering begins at 0 — when the length of extended_list is 70, the indexes are 0–69).

    我们使用内置的range()函数获取列表中每个len()项目的索引(回想一下,Python编号从0开始-当extended_list的长度为70时,索引为0–69) 。

    We create a key-value pair in our dictionary, for each indexed list element. Our key is the value of the list element (a string representing a color). The value paired to the key is assigned from the count of how many times that element appears in the list.

    我们在字典中为每个索引列表元素创建一个键值对。 我们的关键是list元素的值(代表颜色的字符串)。 与该键配对的值是根据该元素在列表中出现的次数来分配的。

    See if you can make out the subtasks in the code snippet, below:

    查看下面的代码片段是否可以区分出子任务:

    # running our loopfor c in range(len(extended_list)): colors_dict[extended_list[c]] = extended_list.count( extended_list[c] )

    步骤6:查看字典。 (Step 6: View the dictionary.)

    Finally, we print our dictionary to see how many of each color is on our list.

    最后,我们打印字典以查看列表中每种颜色的数量。

    # viewing our dictionaryprint(colors_dict)> {'gold': 13, 'blue': 7, 'light blue': 15, 'black': 12, 'green': 9, 'red': 7, 'silver': 7}

    结论 (Conclusion)

    Our approach for this article enabled us to introduce or review some of the characteristics of Python lists, including discussing uses for the len() and range() list methods. In addition, we looked at some of the data types that lists can hold, operations that we may perform on them, and how lists are indexed. We then turned our attention to the collection of key-value pairs that make up Python dictionaries. We discussed how dictionaries are structured and explored how unique list elements may be represented as dictionary keys. We also introduced techniques for extending lists and changing the order of list elements. Finally, we completed our todo-list with a walk through a code example, where we used a Python dictionary to present a count of the number of times each color occurs on our extended list.

    本文的方法使我们能够介绍或回顾Python列表的一些特征,包括讨论len()和range()列表方法的用法。 此外,我们研究了列表可以保存的某些数据类型,我们可能对它们执行的操作以及如何为列表建立索引。 然后,我们将注意力转向构成Python字典的键值对的集合。 我们讨论了字典的结构,并探讨了如何将唯一列表元素表示为字典键。 我们还介绍了扩展列表和更改列表元素顺序的技术。 最后,我们通过一个代码示例完成了待办事项列表,在该示例中,我们使用Python字典来表示每种颜色在扩展列表中出现的次数。

    If you already have a randomized list, to begin with, and leave out all of our related discussion, our approach will enable you to solve this problem in very few lines of code. Of course, there is more than one way to accomplish our task, in Python. What other approaches might you take?

    首先,如果您已经有一个随机列表,而忽略了所有相关讨论,那么我们的方法将使您能够用很少的几行代码来解决此问题。 当然,在Python中,有多种方法可以完成我们的任务。 您还可以采用哪些其他方法?

    翻译自: https://medium.com/@jameld.pro/create-a-dictionary-from-a-list-65742246ab4b

    列表创建字典

    Processed: 0.009, SQL: 8