【问题标题】:How to add an integer to each element in a list?如何将整数添加到列表中的每个元素?
【发布时间】:2012-03-07 10:41:29
【问题描述】:

如果我有list=[1,2,3] 并且我想将1 添加到每个元素以获得输出[2,3,4], 我该怎么做?

我假设我会使用 for 循环,但不确定具体如何。

【问题讨论】:

    标签: python loops addition


    【解决方案1】:
    new_list = [x+1 for x in my_list]
    

    【讨论】:

    • 这个演讲解释了它:关于 Python 名称和值的事实和神话:nedbatchelder.com/text/names1.html
    • √ 很棒的信息。大开眼界。
    • @DaniSpringer 因为您没有分配给列表。与lst = [1, 2, 3]; e = lst[0]; e += 1 相同。 e 没有任何关于它来自何处的信息,它只是一个变量,列表中的一个元素已分配给它。分配其他内容后,列表lst 不会改变。
    • 这个答案看起来和我很相似。
    • 和对应的懒计算一个:new_list = (x+1 for x in my_list)
    【解决方案2】:
    >>> mylist = [1,2,3]
    >>> [x+1 for x in mylist]
    [2, 3, 4]
    >>>
    

    list-comprehensions python.

    【讨论】:

      【解决方案3】:

      关于列表理解的其他答案可能是简单加法的最佳选择,但如果您有一个更复杂的函数需要应用于所有元素,那么map 可能是一个不错的选择。

      在你的例子中是:

      >>> map(lambda x:x+1, [1,2,3])
      [2,3,4]
      

      【讨论】:

      • map(1 .__add__, ...) 也可以。请注意,您需要在 1. 之间留一个空格,以防止解析器认为它是一个浮点数
      • 我最终用一个列表“容器”封装它以摆脱地图对象list(map(lambda x:x+1, [1,2,3]))
      【解决方案4】:

      Python 2+:

      >>> mylist = [1,2,3]
      >>> map(lambda x: x + 1, mylist)
      [2, 3, 4]
      

      Python 3+:

      >>> mylist = [1,2,3]
      >>> list(map(lambda x: x + 1, mylist))
      [2, 3, 4]
      

      【讨论】:

        【解决方案5】:

        编辑:这不是就地的

        首先,不要对变量使用“列表”一词。它隐藏了关键字list

        最好的方法是使用拼接来完成,注意[:] 表示拼接:

        >>> _list=[1,2,3]
        >>> _list[:]=[i+1 for i in _list]
        >>> _list
        [2, 3, 4]
        

        【讨论】:

        • 这对于更改现有列表很有用,但它仍然会生成一个新列表。使用生成器来避免不必要的列表创建是否有点不安全?即_list[:]=(i+1 for i in _list).
        • 仍然会创建一个新列表,如果没有 for 循环,我认为不可能就地完成
        • 你认为_list[:]=(i+1 for i in _list)为什么会创建一个新列表?
        • 我的意思是,它已经到位,但暂时它会为 rhs 创建一个全新的列表。看到这些答案:stackoverflow.com/questions/4948293/…stackoverflow.com/questions/11877212/…
        • 我明白你的意思。将临时序列称为列表使我感到困惑。我们真的知道它的类型吗?那不是特定于实现的吗?
        【解决方案6】:
        >>> [x.__add__(1) for x in [1, 3, 5]]
        3: [2, 4, 6]
        

        我的目的是公开列表中的项目是否为整数,它支持各种内置函数。

        【讨论】:

          【解决方案7】:

          如果你想使用numpy,还有另一种方法如下

          import numpy as np
          list1 = [1,2,3]
          list1 = list(np.asarray(list1) + 1)
          

          【讨论】:

            【解决方案8】:
            list = [1,2,3,4,5]
            
            for index in range(len(list)):
                  list[index] = list[index] +1
            
            print(list)
            

            【讨论】:

              【解决方案9】:

              遇到了一种效率不高但独特的方法。所以分享它。是的,它需要额外的空间来放置另一个列表。

              from operator import add
              test_list1 = [4, 5, 6, 2, 10]
              test_list2 = [1] * len(test_list1)
              
              res_list = list(map(add, test_list1, test_list2))
              
              print(test_list1)
              print(test_list2)
              print(res_list)
              
              #### Output ####
              [4, 5, 6, 2, 10]
              [1, 1, 1, 1, 1]
              [5, 6, 7, 3, 11]
              

              【讨论】:

              • “添加”从何而来?
              • 添加应该从运营商导入,from operator import add
              【解决方案10】:

              上面的很多答案都很好。我还看到了一些可以完成这项工作的奇怪答案。此外,最后看到的答案是通过正常循环。这种提供答案的意愿使我找到了itertoolsnumpy,它们将以不同的方式完成相同的工作。

              这里我介绍了不同的方法来完成这项工作,上面没有回答。

              import operator
              import itertools
              
              x = [3, 5, 6, 7]
              
              integer = 89
              
              """
              Want more vairaint can also use zip_longest from itertools instead just zip
              """
              #lazy eval
              a = itertools.starmap(operator.add, zip(x, [89] * len(x))) # this is not subscriptable but iterable
              print(a)
              for i in a:
                print(i, end = ",")
              
              
              # prepared list
              a = list(itertools.starmap(operator.add, zip(x, [89] * len(x)))) # this returns list
              print(a)
              
              
              
              # With numpy (before this, install numpy if not present with `pip install numpy`)
              import numpy
              
              res = numpy.ones(len(x), dtype=int) * integer + x # it returns numpy array
              res = numpy.array(x) + integer # you can also use this, infact there are many ways to play around
              print(res)
              print(res.shape) # prints structure of array, i.e. shape
              
              # if you specifically want a list, then use tolist
              
              res_list = res.tolist()
              print(res_list)
              
              

              输出

              >>> <itertools.starmap object at 0x0000028793490AF0> # output by lazy val
              >>> 92,94,95,96,                                     # output of iterating above starmap object
              >>> [92, 94, 95, 96]                                 # output obtained by casting to list
              >>>                   __
              >>> # |\ | |  | |\/| |__| \ /
              >>> # | \| |__| |  | |     |
              >>> [92 94 95 96]                                    # this is numpy.ndarray object
              >>> (4,)                                             # shape of array
              >>> [92, 94, 95, 96]                                 # this is a list object (doesn't have a shape)
              

              唯一强调使用 numpy 的原因是人们应该始终使用 numpy 之类的库进行此类操作,因为它对于非常大的数组具有高效的性能。

              【讨论】:

                【解决方案11】:
                import numpy as np
                
                np.add([1, 2, 3], 1).tolist()
                

                给了

                [2, 3, 4]
                

                【讨论】:

                  【解决方案12】:

                  以防万一有人在寻找仅使用内置插件而不使用 lambdas 的解决方案:

                  from functools import partial
                  from operator import add
                  
                  
                  my_list = range(1, 4)  # list(my_list) #=> [1, 2, 3]
                  my_list_plus_one = list(map(partial(add, 1), my_list)  # [2, 3, 4]
                  

                  【讨论】:

                    猜你喜欢
                    • 2021-10-04
                    • 2018-10-15
                    • 2017-09-27
                    • 2018-03-09
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2018-08-11
                    相关资源
                    最近更新 更多