【问题标题】:Why is my for loop only returning last value?为什么我的 for 循环只返回最后一个值?
【发布时间】:2020-01-12 22:32:39
【问题描述】:
for desc in database.desc:
    if sub in desc:
        station = desc.split(";")
        station.pop(0)
        station.pop(0)
        station.pop(1)
        if len(station) > 1:
            station.pop()
        print(station)
    else:
        ""

print(station)

第一个打印语句给出了我想要的所有值。当我在 for 循环之外打印语句时。它只给了我 csv 文件的最后一个值。

【问题讨论】:

  • station 在循环的每次迭代中都会被覆盖,因此一旦循环结束,它的值将是它设置的最后一个值,这将是循环中分配的最后一个值。如果要保留所有值,请使用列表并附加到它。

标签: python pandas for-loop


【解决方案1】:

因为在 for 循环的每次迭代中,您都将 desc.split(";") 的值分配给 station,因此它在每个时刻都保存当前值,当 for 循环结束时,它保存的值是最后一个,然后打印出来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 2015-06-17
    • 2012-11-13
    相关资源
    最近更新 更多