my_list = [2, 3, -3, -2, 4, -4, -1, -2, -5, -6, 7, 2, 4]
def custom_counter(my_list):
sum = 0
for num in my_list:
sum += num
if not -5 < sum < 5:
yield "x" if sum > 0 else "y"
sum = 0
print(list(custom_counter(my_list)))
import pandas as pd
def custom_counter(my_list):
total = 0
label = "A"
for num in my_list:
total += num
if not -5 < total < 5:
label = "X" if total > 0 else "Y"
yield [num, total, label]
total = 0
label = "A"
else:
yield [num, total, label]
my_list = [3.0, 2.5, -4.1, 1.2, -3.8, 2.9, -1.0, 3.4, 3.6, 2.7]
df = pd.DataFrame(custom_counter(my_list), columns=['Data','CumSum','Label'])
print(df)
输出
Data CumSum Label
0 3.0 3.0 A
1 2.5 5.5 X
2 -4.1 -4.1 A
3 1.2 -2.9 A
4 -3.8 -6.7 Y
5 2.9 2.9 A
6 -1.0 1.9 A
7 3.4 5.3 X
8 3.6 3.6 A
9 2.7 6.3 X
data = [1.7, -0.2, 1.5, 2.3, 1.8, -4.5, 1.6, -3.9]
s, idx = 0, 0 # s will hold the running sum, idx will hold the starting index for each iteration
for i, num in enumerate(data):
s += num # adding to the sum
if abs(s) >= 5: #checking if sum is >= 5 or <= -5
print((idx, i), s) # prints the range the sum was found and the sum
s, idx = 0, i + 1 # resets the index and sum
函数,该函数将生成一个生成器,该生成器将在每次满足条件时返回x和y标签。在
输出
^{pr2}$更新,因为您完全改变了问题的上下文和输出期望值
对你的问题有了好几个答案,然后你改变了问题的范围,要求一些不同的东西。这应该是一个新的问题,但由于你已经更新了你的问题,我已经更新了我的答案,以反映你更新的问题。在
输出
这里有一个使用
abs
和for循环的非常简单的方法:我添加了一些注释来帮助遵循代码打印:
^{pr2}$我建议使用列表并按索引访问,而不是使用}。这可以使用上面的方法通过附加到列表而不是打印来完成。在
x
和{下面列出一个列表:
当然,您可以使用枚举方法在原始代码块中包括索引甚至值,但我假设这正是您要查找的。在
下面是一个使用生成器函数的简单明了的方法:
^{pr2}$
快速检查添加每个间隔内的累计和:
相关问题 更多 >
编程相关推荐