Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么要创建x变量?代码中使用的逻辑是什么_Python_Python 3.x_List_Enumerate - Fatal编程技术网

Python 为什么要创建x变量?代码中使用的逻辑是什么

Python 为什么要创建x变量?代码中使用的逻辑是什么,python,python-3.x,list,enumerate,Python,Python 3.x,List,Enumerate,这看起来很简单,但需要查看enumerate上的实现: enumerate()is python内置模块提供了以生成器格式管理列表索引的能力,这是一种节省内存的方法 现在检查枚举在这种情况下的工作方式: 名单(列举(姓名)) [(0,'Rachael Green'), (1,“古德费罗·伊恩”), (2,“Tedd Crock”), (3,“米娜·约瑟夫”)] 这是一个元组列表,其索引分配给“0”中的名称列表 for循环正在遍历此列表,并创建一个字符串[此处在“x”中],该字符串根据薪水标记名

这看起来很简单,但需要查看enumerate上的实现:
enumerate()
is python内置模块提供了以生成器格式管理列表索引的能力,这是一种节省内存的方法

现在检查枚举在这种情况下的工作方式:

名单(列举(姓名))

[(0,'Rachael Green'), (1,“古德费罗·伊恩”), (2,“Tedd Crock”), (3,“米娜·约瑟夫”)]

  • 这是一个元组列表,其索引分配给“0”中的名称列表
  • for循环正在遍历此列表,并创建一个字符串[此处在“x”中],该字符串根据薪水标记名称
  • 附加空列表“人员工资”

最后,您将有一个“人员工资”列表,其中包含提到的姓名和工资

在此处创建变量x,以创建一个临时字符串,该字符串将附加到列表中。Enumerate将创建一个元组,元组中的数字类似于一个索引,与迭代的每个项配对(这就是循环需要2个值
(i,j)
。然后,代码将获取Enumerate数字并将其用作工资的索引

我建议1.创建一个包含姓名和薪水的字典,2.代码不需要x,只需执行
people\u salaries.append(j+'$'+str(salaries[I])

将for循环更改为工资中i的枚举,而不是使用dictionary方法

names = [ "Rachael Green", "Goodfellow Ian", "Tedd Crock", "Mina Joseph"]
salaries = [10260 , 41571 , 71211 , 52141 , 35781]
people_salaries = []
 
for i , j in enumerate(names):
    x = j + " $" + str(salaries[i])
    people_salaries.append(x)
然后加上

for i in people_dict.keys()
在上述代码中

people_salaries.append(i + '$' + str(people_dict[i]))
从for循环解释:

names = [ "Rachael Green", "Goodfellow Ian", "Tedd Crock", "Mina Joseph"]
salaries = [10260 , 41571 , 71211 , 52141 , 35781]
people_salaries = []
 
for i , j in enumerate(names):
    x = j + " $" + str(salaries[i])
    people_salaries.append(x)
现在在最后一句话中:

for i , j in enumerate(names): 
  # this enumerate defragment the items of the list you give here name has several             
  # name and all the names will will be passed to j one by one and
  #  index value will be passed to i

x = j + " $" + str(salaries[i])
  # In this statemnt x is string value in which name and salary along with us currency 
  #is assigned. 
  #for eg: in first iteration 
  # x = "Rachael Green" + "$" + str(10260)

这发生在名称的末尾

您必须询问编写代码的人为什么决定创建名为
x
的变量。关于此代码中使用的逻辑,您到底不清楚什么?Noep,很抱歉,上面的代码元组中没有给出,最终结果将显示在列表中,因为他将所有字符串附加到de>人员工资列表。
  people_salaries.append(x) # in this all x string will be appended