Python For循环返回最后一个值解释 [英] Python For Loops Returning Last Value | Explanation

查看:611
本文介绍了Python For循环返回最后一个值解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题已解决,但是如果有人可以解释为什么 for循环在python中做到这一点,并且还有更优雅的方法,那将是很好的.非常抱歉,这是一个愚蠢的问题-我已尽力尝试多种方法并查看相关问题,但是我仍然不确定为什么它不起作用.

I have a simple problem which I've solved but it would be great if someone could explain why for loops do this in python and if there is a more elegant way. Really sorry if this is a dumb question - I have done my best to try multiple methods and look at related questions, but I still unsure why it doesn't work.

我已经阅读了这篇文章,但是并不能完全解释我的问题:

I've read this post, but it doesn't quite explain my issue: for loop only returning the last word in a list of many words

如果我打印 x,它会完美地返回每个月的名字.

If I print x, it returns every month name perfectly.

monthName = []

for i in df["Month_Number"]:
    x = calendar.month_abbr[i]
    print(x)

以下内容将结果(月份名称)存储在一个干净的列表中(很棒).

The below stores the result (month names) it in a nice clean list (which is great).

monthName = []

for i in df["Month_Number"]:
    x = calendar.month_abbr[i]
    monthName.append(x)

然后我将通过以下方法继续解决我的问题:

I would then go on to solve my problem by doing this:

df["Month_Name"] = monthName

为什么当我集成到循环中时,以下内容仅返回"NONE" ?

monthName = []

for i in df["Month_Number"]:
    x = calendar.month_abbr[i]
    df["Month_Name"] = monthName.append(x)

为什么以下内容仅返回最后一个值:

for i in df["Month_Number"]:
    df["Month_Name"] = calendar.month_abbr[i]

我(在某种程度上)理解了为什么append却不返回任何值,但是对理解为什么其他方法仅返回LAST值更感兴趣.

I understand (to some degree) as to why append returns none, but was more interested in understanding why other approaches only return the LAST value.

推荐答案

第一种方法,append()不返回任何内容,因此其返回值将为None.

First way, append() doesn't return anything, so its return value will be None.

第二种方法,什么也没有返回",您要在循环中覆盖值,然后仅在最后一次迭代后检查 entire df["Month_Name"]列的值,根据定义,将是最后一个值.

Second way, nothing is "being returned", you are overwriting the value within a loop, then only inspecting the value of the entire df["Month_Name"] column after the final iteration, which by definition, will be the last value.

我认为在这里使用循环是错误的方法,应该改用applymap函数,但是如果您要循环,我可能会建议

I think using loops is the wrong approach here, you should be using apply or map functions instead, but if you wanted a loop, I might suggest this

df["Month_Name"] = [calendar.month_abbr[i] for i in df["Month_Number"]]

这篇关于Python For循环返回最后一个值解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆