【问题标题】:How to shorten Python for loop?如何缩短 Python for 循环?
【发布时间】:2022-01-10 08:30:06
【问题描述】:

我创建了一个 for 循环,我想进一步简化我的循环。这些是我为我的 for 循环编写的代码:

for i in range(0,len(df.index)):
    reported_claims.iloc[i,(i+1)-1] = df.iloc[i, 1] * df.iloc[i, 2] * chance[0]
    reported_claims.iloc[i,(i+2)-1] = df.iloc[i, 1] * df.iloc[i, 2] * chance[1]
    reported_claims.iloc[i,(i+3)-1] = df.iloc[i, 1] * df.iloc[i, 2] * chance[2]

我收到了这个输出:

我尝试了 2 种方法来简化我的 for 循环:

n = 1
j = 0
for i in range(0,len(df.index)):
    reported_claims.iloc[i,(i+n)-1] = df.iloc[i, 1] * df.iloc[i, 2] * chance[j]; n+=1; j+=1
for i in range(0,len(df.index)):
    for j in range(0,len(chance)):
        for n in range(1,4):
            reported_claims.iloc[i,(i+n)-1] = df.iloc[i, 1] * df.iloc[i, 2] * chance[j]

但我收到的输出与我原来的不匹配:

谁能告诉我如何简化我原来的 for 循环?非常感谢您的帮助!

【问题讨论】:

    标签: python for-loop simplify


    【解决方案1】:

    试试这个:

    for i in range(0,len(df.index)):
        for j in range(0,len(chance)):
                    reported_claims.iloc[i,j+1] = df.iloc[i, 1] * df.iloc[i, 2] * chance[j]
    

    【讨论】:

    • 感谢您的建议。我已经尝试了代码,但不幸的是它与我的原始输出不匹配。
    • 用这个替换第三行怎么样:reported_claims.iloc[i,j] = df.iloc[i, 1] * df.iloc[i, 2] * chance[j] ?跨度>
    • 我试过了。数字是正确的,但它们是垂直的,而不是像我的原始输出那样对角线。
    • 实际上我现在通过在第三行添加 (i + 1) - 1 到 j 来让它工作。非常感谢你的帮助!报告的_claims.iloc[i,(j+i+1)-1] = df.iloc[i, 1] * df.iloc[i, 2] * chance[j]
    • 不客气,对于您未来可能出现的问题,请尝试提及问题的简要模式,以便您更快地找到答案。
    猜你喜欢
    • 2011-12-23
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多