【发布时间】: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()函数。 -
请尽量减少您的代码以重现您的问题 - 例如,导入是无用的。另外,清楚地解释你应该如何从你的输入中构建你的输出。