为什么创建 x 变量以及此代码中使用的逻辑是什么

问题描述

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)

解决方法

这里创建变量 x 是为了创建一个临时字符串,该字符串将附加到列表中。 Enumerate 将创建一个带有数字的元组,例如与迭代的每个项目配对的索引(这就是循环需要 2 个值 (i,j) 的原因。然后,代码将采用枚举数并将其用作工资的索引。

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

将 for 循环而不是 enumerate 改为 for i in salaries 或简单地使用字典方法

for i in people_dict.keys()

然后附加

people_salaries.append(i + '$' + str(people_dict[i]))
,

这看起来很简单,但需要看一下 enumerate 上的实现: enumerate() 是 python 内置模块,能够以生成器格式管理列表的索引,这是一种内存高效的方式。

现在检查枚举在这种情况下是如何工作的:

list(enumerate(names))

[(0,'瑞秋·格林'),(1,'Goodfellow Ian'),(2,“泰德·克罗克”), (3,'米娜约瑟夫')]

  • 它是一个元组列表,其索引分配给来自“0”的名称列表
  • for 循环遍历此列表并创建一个字符串 [here in 'x'],其中标记 Name 与工资
  • 附加空列表“people_salaries”

最后,您将列出“people_salaries”,其中提到了姓名和薪水

,

在上面的代码中,

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 循环说明:

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)

现在在最后一句话:

  people_salaries.append(x) # in this all x string will be appended

这发生在名字的末尾

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...