Python For 循环仅将最后一个值追加到列表中

标签 python list for-loop

我有一个循环,将一个列表的值设置为另一个列表的值,虽然我能够使用当前的代码实现此目的,但它只是将最后一组值附加到我的列表中。我的设置中可能存在哪些问题会导致此行为?

这是我的数据格式:

print(df_full_raw_format) # Data Set being set to worksheet_range values

<class 'pandas.core.frame.DataFrame'>
     b_clicks  b_cpc  date_string
0    b_clicks  b_cpc  date_string
1          72   2.43   2018-01-01
2         232    2.8   2018-01-02
3         255    2.6   2018-01-03
4         249   2.65   2018-01-04
5         202   2.86   2018-01-05

这是我的 worksheet_range 格式:

[<Cell R1C1 ''>, <Cell R2C1 ''>, <Cell R3C1 ''>,....]

这是我的带有 for 循环的函数:

update_raw_data_sheet(df_full_raw_format)

def update_raw_data_sheet(data_set):
    for col_val, col_name in zip(gs_columns, columns):
        updated_values = [] # List storing the combined list values
        column_data = data_set[col_name].values.tolist(); # col_name = ['b_clicks', 'b_cpc', 'date_string']
        print("COLUMN DATA")
        print(column_data)
        worksheet_range = worksheet.range(1, col_val, len(column_data), col_val); # [row_start, col_start, row_end, col_end]
        print(worksheet_range)
        for cell, data in zip(worksheet_range, column_data):
            cell.value = data # <Cell R1C1 '2018-01-01'>...
            print(cell)
            updated_values.append(cell)

    print(updated_values)

这是控制台:

(Loop 1)
COLUMN DATA
['date_string', '2018-01-01', '2018-01-02', '2018-01-03', ...] # print(column_data)
[<Cell R1C1 ''>, <Cell R2C1 ''>, <Cell R3C1 ''>,...] # print(worksheet_range)
<Cell R1C1 'date_string'> # print(cell)
<Cell R2C1 '2018-01-01'>
<Cell R3C1 '2018-01-02'>
<Cell R4C1 '2018-01-03'>
... (Loop 2)
COLUMN DATA
['b_clicks', '72', '232', '255', ...]
[<Cell R1C2 ''>, <Cell R2C2 ''>, <Cell R3C2 '', ...]
<Cell R1C2 'b_clicks'>
<Cell R2C2 '72'>
<Cell R3C2 '232'>
... (Loop 3)
COLUMN DATA
['b_cpc', 2.43, 2.8,...]
[<Cell R1C3 'b_cpc'>, <Cell R2C3 '2.43'>, <Cell R3C3 '2.8'>, ...]
<Cell R1C3 'b_cpc'>
<Cell R2C3 2.43>
<Cell R3C3 2.8>
(Post-Loop)
[<Cell R1C3 'b_cpc'>, <Cell R2C3 2.43>, <Cell R3C3 2.8>, ...] # print(updated_values)

它错过了前两个循环的值,但完美地捕获了数组中的第三个值。

最佳答案

updated_values = []

应该在 def 语句之后的外部循环,否则您会覆盖每次迭代中添加到列表中的值。


def update_raw_data_sheet(data_set):
    updated_values = []
    # ...

关于Python For 循环仅将最后一个值追加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53784325/

相关文章:

python - 如何打印列表中字符串中的单词?在 Python 中

javascript - 为什么 For..in(loop) 总是破坏它所在的函数?

php - 无需准备语句即可缩短代码

python - 对于旧式和新式,该类层次结构的 MRO 是否相同?

Python SSL 服务器给我 "501 Unsupported method GET"

python - 使用 Django 获取已连接用户的列表

python - OpenCL 矩阵乘法 - 得到错误的答案

python - 根据其他列表的一些属性创建一个列表

PYTHON - 在循环中创建多个列表

python - 如何根据长度在Python中从一维列表创建二维列表