【问题标题】:Why x variable is created and what is the logic used in this code为什么创建 x 变量以及此代码中使用的逻辑是什么
【发布时间】:2021-04-08 14:40:01
【问题描述】:
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 的变量。
  • 您对这段代码中使用的逻辑究竟有什么不清楚的地方?

标签: python python-3.x list enumerate


【解决方案1】:

在此处创建变量 x 以创建将附加到列表的临时字符串。 Enumerate 将创建一个元组,其中包含一个数字,例如与每个迭代的项目配对的索引(这就是为什么循环需要 2 个值 (i,j)。然后,代码将获取枚举数字并将其用作薪水的索引。

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

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

for i in people_dict.keys()

然后追加

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

【讨论】:

    【解决方案2】:

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

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

    列表(枚举(名称))

    [(0, '瑞秋格林'), (1,“好家伙伊恩”), (2,“泰德瓦罐”), (3, '米娜约瑟夫')]

    • 它是一个元组列表,索引分配给从“0”开始的名称列表
    • for 循环正在遍历此列表并创建一个字符串 [here in 'x'] 标记 Name 与薪水
    • 追加空列表“people_salaries”

    最后,您将列出包含姓名和薪水的“people_salaries”列表

    【讨论】:

    • 不,抱歉,但在上面的代码中没有给出元组,最终结果将在列表中,因为他将所有字符串附加到 people_salaries 列表中。
    【解决方案3】:

    在上面的代码中,

    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
    

    这发生在名字的末尾

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 2017-06-28
      • 2014-02-19
      相关资源
      最近更新 更多