【问题标题】:Iterating over a nested list with Python使用 Python 遍历嵌套列表
【发布时间】:2020-08-19 12:01:26
【问题描述】:

我正在尝试使用我的代码更新智能表。我将数据放在一个嵌套列表中,我想每次都将它传递给 new_rows 函数(逐个值)。 当我在网上搜索时,我无法使用常规方法对其进行迭代,因为我认为我错过了一些东西。 现在发生的事情只是发送第一行条目然后停止。 所以我知道它需要遍历嵌套列表并循环执行,但我不知道该怎么做。谁能帮帮我?

import csv
import os
from simple_smartsheet import Smartsheet
from simple_smartsheet.models import Sheet, Column, Row, Cell, ColumnType
data = pd.read_csv(r'C:\Temp\Book1.csv')
df = pd.DataFrame(data, columns=['Name', 'TCU', 'Vendor', 'App', 'App_Version'])
example = df.values.tolist()
print(example)
TOKEN = os.getenv("")
SHEET_ID = "Book1"
smartsheet = Smartsheet("**************")

# retrieve a list of sheets (limited set of attributes)
sheet = smartsheet.sheets.get(SHEET_ID)
print(sheet)
new_rows = [
    Row(
        to_top=True,
        cells=[
            sheet.make_cell("Name", example[0][0]), 
            sheet.make_cell("TCU", example[0][0]),
            sheet.make_cell("Vendor", example[0][0]),
            sheet.make_cell("App",example[0][0]),
            sheet.make_cell("App_Version", example[0][0]),
        ],
    ),
]
smartsheet.sheets.add_rows(sheet.id, new_rows)

【问题讨论】:

    标签: python python-3.x smartsheet-api


    【解决方案1】:

    您只指定列表中的第一个元素,而从不遍历其余元素。

    new_rows = []
    for element in example:
        row = Row(to_top=True,
            cells=[
                sheet.make_cell("Name", element[0]),
                sheet.make_cell("TCU", element[1])
            ])
        new_rows.append(row)
    

    请注意,此示例提供了几种不同的方式来访问您的列表,并且可能需要进行修改以适应 example 中包含的任何内容的形状。

    【讨论】:

      猜你喜欢
      • 2012-11-11
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 2021-03-19
      • 1970-01-01
      相关资源
      最近更新 更多