python - 从列表元组中正确赋值

标签 python dictionary for-loop openpyxl

我有一个基本问题,但无法理解:

prepared_data = ([1, '7303 ', 'product1'], [2, '7304 ', 'product2'], [3, '7534 ', 'product3'], [4, '7652 ', 'product4'])

我想分配这些值,但不知道如何正确排列循环:

for row_num in range(2, len(prepared_data)+2):
    for index in range(len(prepared_data)):
        wb2_ws1.cell(row=row_num, column=1).value = prepared_data[index][0]
        wb2_ws1.cell(row=row_num, column=2).value = prepared_data[index][1]
        wb2_ws1.cell(row=row_num, column=3).value = prepared_data[index][2]
        wb2_ws1.cell(row=row_num, column=4).value = 'John'

程序应填充第二行的单元格。但它总是会覆盖之前的所有值。感谢您的帮助

最佳答案

如果我理解正确,您只需要一个 for 循环,其中 row_numprepared_data 索引的函数。您可以通过使用带有适当起始值的 enumerate 来隐式该函数。

for row_num, (some_int, some_str, some_label) in enumerate(prepared_data, start=2):
    wb2_ws1.cell(row=row_num, column=1).value = some_int
    wb2_ws1.cell(row=row_num, column=2).value = some_str
    wb2_ws1.cell(row=row_num, column=3).value = some_label
    wb2_ws1.cell(row=row_num, column=4).value = 'John'

关于python - 从列表元组中正确赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45149435/

相关文章:

c# - 如何在没有 async/await 的情况下循环异步方法

Java ArrayList - 值,而不是从 ArrayList 中删除的项目

python - 解析 GTF 基因文件

java - 如何从同步映射java将映射条目添加到同步/非同步映射

python - 使用字典中的常见值在 python 中绘制图形

vb.net - 尝试使用 Catch 显示输入错误消息

php - 根据变量创建多个div

python - 在 Bittorrent 中获取 IP 地址

python - 在 Django 中扩展表单?

python - 在全局变量上运行文件