【问题标题】:Add to integers in a list添加到列表中的整数
【发布时间】:2011-06-06 05:16:49
【问题描述】:

我有一个整数列表,我想知道是否可以添加到此列表中的单个整数。

【问题讨论】:

  • 您所说的“添加到单个整数”是什么意思 - 您想将相同的数字添加到给定的一组元素,比如元素 1、5、10 和 23?
  • 没有足够的信息来回答这个问题。 “添加到此列表中的单个整数”是什么意思?
  • 请举例说明您希望列表在手术前后的样子。
  • 令人惊奇的是,这个问题,正如所写的,有 3 票赞成。更令人惊奇的是答案的质量。
  • 这个问题完全看不懂。

标签: python list integer add


【解决方案1】:

nums = [1,2,3,4]

数字 = 数字 + [5]

打印 (nums) #[1, 2, 3, 4, 5]

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

您可以附加到列表的末尾:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

您可以像这样编辑列表中的项目:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

将整数插入列表的中间:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

【讨论】:

  • 这样会报这种错误IndentationError: unindent does not match any outer indentation level
【解决方案3】:

如果您尝试附加数字,例如 listName.append(4) ,这将在最后附加 4 。 但是,如果您尝试获取<int>,然后将其附加为num = 4,后跟listName.append(num),则会出现'num' is of <int> typelistName is of type <list> 的错误。所以在添加之前输入 cast int(num)

【讨论】:

    【解决方案4】:

    这是一个示例,其中要添加的内容来自字典

    >>> L = [0, 0, 0, 0]
    >>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
    >>> for item in things_to_add:
    ...     L[item['idx']] += item['amount']
    ... 
    >>> L
    [0, 1, 1, 0]
    

    这是一个从另一个列表添加元素的示例

    >>> L = [0, 0, 0, 0]
    >>> things_to_add = [0, 1, 1, 0]
    >>> for idx, amount in enumerate(things_to_add):
    ...     L[idx] += amount
    ... 
    >>> L
    [0, 1, 1, 0]
    

    您也可以通过列表理解和 zip 实现上述目标

    L[:] = [sum(i) for i in zip(L, things_to_add)]
    

    这是一个从元组列表中添加的示例

    >>> things_to_add = [(1, 1), (2, 1)]
    >>> for idx, amount in things_to_add:
    ...     L[idx] += amount
    ... 
    >>> L
    [0, 1, 1, 0]
    

    【讨论】:

    • @user12379095,我认为这与这个问题无关。您可以发布一个新问题并包含您的代码吗?
    【解决方案5】:
    fooList = [1,3,348,2]
    fooList.append(3)
    fooList.append(2734)
    print(fooList) # [1,3,348,2,3,2734]
    

    【讨论】:

      【解决方案6】:

      是的,这是可能的,因为列表是可变的。

      查看内置的enumerate() 函数以了解如何遍历列表并找到每个条目的索引(然后您可以使用它来分配给特定的列表项)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-05
        • 2019-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        相关资源
        最近更新 更多