【问题标题】:How to append a nested list in Python?如何在 Python 中附加嵌套列表?
【发布时间】:2014-10-27 20:12:07
【问题描述】:

如何将第二行中的所有数据除以二?

recipe  = [
    ['eggs', 'flour', 'meat'],
    [4, 250, 5],
    ['large','grams', 'kg'],
]

我尝试过从

for row[2] in recipe:

但我收到一条错误消息:

Traceback(最近一次调用最后一次):

文件“/Users/g/Documents/reicpe.py”,第 7 行,在 对于肉馅饼中的第 [2] 行:

NameError: name 'row' 没有定义

【问题讨论】:

    标签: python list nested


    【解决方案1】:

    您也可以使用 list comprehension 并在没有 for-loop 的情况下在一行中完成:

    recipe[1] = [num / 2 for num in recipe[1]] 
    

    代码说明[num / 2 for num in recipe[1]]

    • recipe[1]:这是一个列表,它是recipe列表的第二个元素

      recipe的第二个元素是:[4, 250, 5]

    • for num in recipe[1]:这意味着我们要循环遍历recipe[1] 的元素,所以num 它是一个变量,它的值在每次迭代中都会随着列表元素的变化而变化。

    • num / 2: 很明显我们得到 num 并除以 2

    【讨论】:

      【解决方案2】:
      recipe  = [
          ['eggs', 'flour', 'meat'],
          [4, 250, 5],
          ['large','grams', 'kg'],
      ]
      

      如果你想将数量除以二,并改变你存储的内容,把它放在一边作为字典会好得多:

      for quantity, index in enumerate(recipe[1])
          recipe[1][index] = quantity/2
      

      更好的方法是使用字典,它允许您为数据项命名:

      recipe = {"eggs":{"quantity":4, "measurement":"large"},
               "flour":{"quantity":250,"measurement":"grams"}, 
               "meat":{"quantity":5,"measurement":"kg"}}
      

      现在除以二变成:

      for ingredient in recipe:
          recipe[ingredient]["quantity"] = recipe[ingredient]["quantity"]/2
      

      并打印配方变为:

      for ingredient in recipe:
          print "{} {} {}".format(recipe[ingredient]["quantity"], recipe[ingredient]["measurement"], ingredient)
      

      这会生成:

      4 large eggs
      250 grams flour
      5 kg meat
      

      并且不关心索引号等。

      【讨论】:

        【解决方案3】:

        recipe[1] 为您提供配方列表中的第二个列表。请记住,列表索引始终以 0 开头。

        然后:

        for row in recipe[1]:
        

        将使用row 进行迭代,获取recipe[1] 中每个值的值。

        【讨论】:

          【解决方案4】:

          您正在尝试迭代错误的部分。当您使用语句:for i in list 时,i 被创建为一个新变量(就像您刚刚声明了i = 5)。因此,此时它没有元素 5 的 getter(索引或其他)(并且它不是有效的变量名)。

          要解决您的迭代问题,请尝试:

          for row in mylist[index]:

          这将遍历 mylist 中 index 处的列表,当然请记住列表是 0 索引的(您的数字在索引 1 处)。

          不过,您很快就会在更新数组中的值时遇到另一个问题,因为该过程会按照您的操作方式创建一个副本。一个简单的解决方法是使用enumerate(但我会留给你在给你之前尝试一下!)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-11-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-04-27
            相关资源
            最近更新 更多