简体   繁体   English

使用 Python 遍历嵌套列表

[英]Iterating over a nested list with Python

I'm trying with my code to update smartsheet.我正在尝试使用我的代码来更新智能表。 I've got my data in a nested list and I want to pass it to the new_rows function each time (value by value).我的数据在一个嵌套列表中,我想每次都将它传递给 new_rows function(逐个值)。 I couldn't get it to iterate with regular methods as I've searched online because I think I missed something.当我在网上搜索时,我无法使用常规方法对其进行迭代,因为我认为我错过了一些东西。 What happens now it just sends the first-row entry and then stops.现在发生的事情只是发送第一行条目然后停止。 So i understand it needs to iterate over the nested list and do it in a loop but i couldn't figure out how to do that.所以我知道它需要遍历嵌套列表并循环执行,但我不知道该怎么做。 Can anyone assist me?任何人都可以帮助我吗?

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)

You are only specifying the first element in your list, and never iterating over the remaining elements.您只指定列表中的第一个元素,而永远不会迭代剩余的元素。

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)

Note that this example provides a couple different ways to access your list, and might need to be modified to fit the shape of whatever is contained inside example .请注意,此示例提供了几种不同的方式来访问您的列表,并且可能需要进行修改以适应example中包含的任何内容的形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM