【问题标题】:How to insert an element after every other element in python list如何在python列表中的每个其他元素之后插入一个元素
【发布时间】:2020-07-09 15:52:42
【问题描述】:

您好,我想知道如何使用 for 循环遍历列表并在新列表中的每个元素之后插入一个元素。

我看过这个链接Insert element in Python list after every nth element

但是当我尝试该方法时,它在我的代码中实现时给了我完全相同的问题

"""
Created on Sat Mar 28 20:40:37 2020

@author: DeAngelo
"""

import math 
import matplotlib.pyplot as plt
import numpy as np
from numpy import sqrt
from quadpy import quad
import scipy.integrate as integrate
import scipy.special as special

experiment = [1,2,3,4,5]
count = len(experiment)

after = []
new = []
for i in range(0,count-1):
    average2 = (experiment[i] + experiment[i+1])/2
    new.append(average2)

print(experiment)

for i in range(0,count-1):
      just = experiment.insert(i+1,new[i])

print(new,'\n')      
print(experiment)

1st print(experiment) -> [1, 2, 3, 4, 5]

print(new,'\n') -> [1.5, 2.5, 3.5, 4.5]2nd, print(experiment) -> [1, 1.5, 2.5, 3.5, 4.5, 2, 3, 4, 5]

但我希望它是 [1,1.5,2,2.5,3,3.5,4,4.5,5] 我知道我可以使用合并和排序,但我不想因为我正在处理一个大得多的列表,并且无法对其进行排序。这只是我现在的宝贝清单。

我真的很接近我能感觉到它,就像第六感......非常感谢任何帮助和指导。非常感谢小可爱

【问题讨论】:

  • 看看zip()函数。
  • 请尽量减少您的代码以重现您的问题 - 例如,导入是无用的。另外,清楚地解释你应该如何从你的输入中构建你的输出。

标签: python list insertion


【解决方案1】:

你可以使用这个单行列表理解

from itertools import zip_longest

a = [1,2,3,4,5]
b = [1.5, 2.5, 3.5, 4.5]
flat_list = [val for sublist in zip_longest(a,b) for val in sublist if val]

输出 = [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]

【讨论】:

    【解决方案2】:

    为了尝试使用列表理解一次生成所需的输出列表,我提供了以下功能:

    e = [1, 2, 3, 4]
    
    r = [e[i] if j == 0 else sum(e[i:i+2])/2. for i in range(len(e)) for j in range(min(len(e) - i, 2))]
    
    assert r == [1, 1.5, 2, 2.5, 3, 3.5, 4]
    

    我使用嵌套的 for 循环只是为了在将原始元素传递到输出和计算后续元素的平均值之间切换。

    【讨论】:

      【解决方案3】:

      对我来说,这看起来像是来自itertools recipesroundrobin 的任务:

      from itertools import cycle, islice
      def roundrobin(*iterables):
          "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
          # Recipe credited to George Sakkis
          pending = len(iterables)
          nexts = cycle(iter(it).__next__ for it in iterables)
          while pending:
              try:
                  for next in nexts:
                      yield next()
              except StopIteration:
                  pending -= 1
                  nexts = cycle(islice(nexts, pending))
      
      a = [1, 2, 3, 4, 5]
      b = [10, 20, 30, 40]
      ab = list(roundrobin(a,b))
      print(ab)
      

      输出:

      [1, 10, 2, 20, 3, 30, 4, 40, 5]
      

      请注意,roundrobin 可能用于交错超过 2 个迭代,并且总是在最长的一个处终止。当您处理更大的列表时,创建generator 而不是list 的额外好处。

      【讨论】:

        【解决方案4】:
        experiment = [1, 2, 3, 4, 5]
        count = len(experiment)
        
        for i in range(count - 1):
            experiment.insert(2*i+1, (experiment[2*i] + experiment[2*i+1])/2)
        
        print(experiment)
        

        【讨论】:

          【解决方案5】:

          对于大型数据集,多次插入列表中间会非常慢。看来您可以像现在一样建立一个新列表:

          first = [1, 2, 3, 4, 5]
          second = []
          for i in range(0, len(first) - 1):
              avg = (first[i] + first[i+1]) / 2
              second.append(first[i])
              second.append(avg)
          second.append(first[-1])
          
          print(second)
          

          哪些打印:

          [1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5]
          

          【讨论】:

          • 我只想对你表示感谢。你真的帮了我。我只是好奇second.append(first[-1]) 做了什么。我不明白,但它有效,这才是最重要的。 :)
          • 没有问题很高兴为您提供帮助! second.append(first[-1]) 行将first 的最后一个元素添加到second 的末尾。 Python 索引可以是负数,当它们是负数时,它们从右到左(或从后到前),所以 -1 是最后一个元素 -2 是倒数第二个元素,依此类推。
          猜你喜欢
          • 2021-06-27
          • 2015-09-11
          • 2017-01-15
          • 2012-09-21
          • 2012-10-29
          • 1970-01-01
          • 2020-01-16
          • 2018-12-08
          • 1970-01-01
          相关资源
          最近更新 更多