我需要在python中执行以下循环(以伪代码,我正在学习python)
listOfNumbers = [1,2,3]
averagesOfNumbers = [0,0,0]
for i = 1 to 2
averagesOfNumbers [i] = (listOfNumbers [i] + listOfNumbers[i + 1]) / 2
end i
averageOfNumbers看起来像[1.5,2.5,0]。
如何在Python中做到这一点?
答案 0 :(得分:1)
如果这正是您想要的,请查看代码:
List=[1,2,3]
avg=[0]*len(List)
for i in range(len(List)-1):
avg[i]=(List[i]+List[i+1])/2
print(avg)
希望您得到了代码。 输出: [1.5,2.5,0]
答案 1 :(得分:1)
这是在Python中执行的操作:
listOfNumbers = [1,2,3]
averagesOfNumbers = [0,0,0]
# In Python, we start counting from 0.
# So, 2 means 0,1 and in total, that
# is 2 numbers.
for i in range(2):
averagesOfNumbers [i] = (listOfNumbers [i] + listOfNumbers[i + 1])/2
print(averagesOfNumbers)
答案 2 :(得分:1)
哇,太酷了。我以前从未使用过stackoverflow。我一直想知道如何让聪明的人来帮助我!
这是给我正确作业的答案。
计算平均变化,最大增加,最大减少。
i = 0
while (i < rowCount - 1):
diffPL.append(PL[i+1] - PL[i])
i = i + 1
averageChange = sum(diffPL)/len(diffPL)
greatestIncrease = max(diffPL)
greatestDecrease = min(diffPL)
感谢所有提出建议的人。
答案 3 :(得分:0)
我想您想执行以下操作:
listOfNumbers = [1,2,3]
averagesOfNumbers = [0,0,0]
for i in range(len(listOfNumbers)-1):
averagesOfNumbers[i] = (listOfNumbers[i] + listOfNumbers[i+1]) / 2
答案 4 :(得分:0)
list_of_numbers = [1, 2, 3]
averages_of_numbers = [0, 0, 0]
for i in range(0, 2): # this will take indexes 0 and 1
averages_of_numbers[i] = (list_of_numbers[i] + list_of_numbers[i+1]) / 2
print(averages_of_numbers)
答案 5 :(得分:0)
这里最Python化的方法是利用zip
。这样可以避免使用不真正使用的索引:
>>> numbers = [1,2,3]
>>> [sum(pair)/2 for pair in zip(numbers, numbers[1:])]
[1.5, 2.5]
如果您确实需要最后加一个零,则可以手动将其添加:
numbers = [1,2,3]
avg = [sum(pair)/2 for pair in zip(numbers, numbers[1:])]
avg.append(0)
在某些情况下(例如,您不需要列表,但需要一个迭代器),甚至可以更清楚地使用map
:
>>> map(lambda pair: sum(pair)/2, zip(numbers, numbers[1:]))
<map object ...>