【问题标题】:How to append the list in Python for certain index?如何在 Python 中为某个索引附加列表?
【发布时间】:2020-01-06 23:23:50
【问题描述】:

我有一个这样的清单;

list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1] # list of 9 elements

我想要另一个像这样的list2..

list2 = [1, 2, 2, 2, 2, 2, 2, 2, 2, 1] # list of 10 elements

list2 是通过将0th 元素和8th 元素与list1 保持并在list1 中彼此相邻添加相邻元素而形成的。 这就是我所做的;

list2 = [None] * 10
list2[0] = list2[9] = 1

for idx, i in enumerate(list1):
    try:
        add = list1[idx] + list1[idx+1]
        #print(add) 
        list2[1:9].append(add)
    except:
        pass

print(list2)

但我没有得到想要的输出...实际上 list2 没有更新,我得到了:

[1, None, None, None, None, None, None, None, None, 1]

【问题讨论】:

  • list2[1:9].append(add) 创建一个新列表,然后附加到它,然后立即丢弃该新列表。
  • 你经常这样做吗?性能很重要吗?
  • 是的@蒂姆·理查森。

标签: python python-3.x list numpy


【解决方案1】:

实现所需结果的另一种方法是有效地转移list1,方法是在列表前面添加一个 0 条目,然后将其添加到自身(由 0 条目扩展以匹配长度),使用zip 创建一个可以迭代的元组列表:

list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1]

list2 = [x + y for x, y in zip([0] + list1, list1 + [0])]
print(list2)

输出

[1, 2, 2, 2, 2, 2, 2, 2, 2, 1]

【讨论】:

    【解决方案2】:

    与其他答案类似,但我会在两行代码中使用中间列表(或者如果您不再需要它,只需修改原始列表)以使填充更容易看到:

    list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1]
    
    lyst = [0, *list1, 0]
    list2 = [prev + cur for prev, cur in zip(lyst, lyst[1:])]
    
    print(list2)
    

    【讨论】:

      【解决方案3】:

      类似的东西呢:

      list2 = list1[:1] + [x + y for x, y in zip(list1[0:], list1[1:])] + list1[-1:]
      

      【讨论】:

      • 如果 OP 对 Python 来说是新的,他们可能是,这可能对他们来说可读
      • @aws_apprentice 也许,但考虑到接受和最赞成的答案与这个答案基本相同,我会说没关系。
      猜你喜欢
      • 2015-11-29
      • 2015-08-03
      • 1970-01-01
      • 2023-03-24
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多