简体   繁体   English

试图弄清楚Python代码

[英]trying to make sense of a Python code

I have a question about the logic of a Python code I've found online that works brilliantly to define a dict from a list formatted in pairs (ie: "one 1/n two 2/n three 3/n" ) The code is: 我对网上找到的Python代码的逻辑有疑问,该代码可以很好地从成对格式化的列表中定义字典(即: "one 1/n two 2/n three 3/n" ),该代码是:

dict_number= {term:int(score) for (term,score) in list_number}

List_number is the list where the values are held, I am not sure I understand how Python understands that everyodd string should be assigned as term and everyeven as a value(well in this case the int of that string)... both term and score have not being defined before this line of code and somehow python manages to make sense of this... any idea how this works? List_number是保存值的列表,我不确定我是否了解Python如何理解应将Everyodd字符串分配为term,将eveneven分配为值(在这种情况下,该字符串的int)... term和score在这行代码之前尚未定义,并且python设法以某种方式理解了这一点...知道这是如何工作的吗?

This is called a dictionary comprehension and was introduced in Python 2.7. 这称为字典理解 ,并在Python 2.7中引入。 It is a shorthand way of creating dictionaries by using expressions. 这是使用表达式创建字典的简便方法。

The longer way of writing that line is: 编写该行的较长方法是:

dict_number = {}  # an empty dictionary

for term,score in list_number:
    dict_number[term] = int(score)

In Python, there are no variables as what you may be used to from other languages. 在Python中,没有其他语言可能会使用的变量。 In most other languages, a variable is a "box" that can hold a specific type of value. 在大多数其他语言中,变量是可以保存特定类型值的“框”。 To hold something in the box, first you have to create the box by describing the type: 要在盒子中放置东西,首先必须通过描述类型来创建盒子:

int x;
x = 1;

Python has the concept of names that point to values. Python具有指向值的名称的概念。 A "variable" in python is simply a name, that can point to any value at any type. python中的“变量”只是一个名称,可以指向任何类型的任何值。 Only values have types, names don't have types. 仅值具有类型,名称不具有类型。 Due to that flexibility, names don't have to be "initialized" in advance. 由于具有这种灵活性,因此不必预先“初始化”名称。 You simply use them when you need them; 您仅在需要时使用它们。 and Python will take care of the rest. Python将负责其余的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM