【问题标题】:Iterate through Multiple Lists and assign Variables based on each iteration遍历多个列表并根据每次迭代分配变量
【发布时间】:2021-03-01 18:49:34
【问题描述】:

我有一个包含 4 列的 csv,我将其转换为 pandas 数据框,然后将每一列设为一个列表。 我正在尝试遍历每个列表并根据 ID 提取数据。 根据它的 ID 类型,它将从 2 个下拉列表中选择 1 个。 我正在尝试制定将 sale_type 变量和 form_code 变量设置为对于列的每次迭代都不同的逻辑。

使用下面的代码,它会自动设置 form_code = 2 和 sale_type ='Push Notification' 完成推送通知列的迭代后,它返回 form_code = 1 和 sale_id 给 Nan 然后停止。

Push Notification sale_id 列表是最后一个列表,应该迭代到最后一个。

def get_report_data(self):
        ("Gathering Report Data...")
        current_date = helpers.currentDate
        report_results = []
        data = pd.read_csv(r'C:\Users\rford\Desktop\sale_ids.csv')
        everyone_ids = data['Everyone'].tolist()
        dd_ids = data['Daily Deal'].tolist()
        targeted_ids = data['Targeted'].tolist()
        push_ids = data['Push Notification'].tolist()
        for sale_id, sale_id, sale_id, sale_id in zip(everyone_ids, dd_ids, targeted_ids, push_ids):
            if sale_id in everyone_ids:
                form_code = 1
                sales_type = "Everyone"
            elif sale_id in dd_ids:
                form_code = 1
                sales_type = "Daily Deal"
            elif sale_id in targeted_ids:
                form_code = 2
                sales_type = "Targeted"
            else: 
                form_code = 2
                sales_type = "Push Notification"
            helpers.driver.find_element_by_xpath('/html/body/form[{}]/div/select/option[@value={}]'.format(form_code, sale_id)).click()```

【问题讨论】:

    标签: python selenium selenium-chromedriver


    【解决方案1】:

    您的“for”循环将丢弃除最后一个列表之外的所有内容。请记住,zip 在每个循环中从每个列表中交付一件事。将这作为 4 个单独的“for”循环执行并不丢人,但如果你真的想这样做,你可以这样做:

        for form_code, sales_type, idlist in (
            ( 1, "Everyone", everyone_ids ),
            ( 1, "Daily Deal", dd_ids ),
            ( 2, "Targets", targeted_ids ),
            ( 2, "Push Notification", push_ids ) ):
            for sale_id in idlist:
                helpers.driver.find_element_by_xpath( ... etc ... )
    

    【讨论】:

    • 这行得通,谢谢,但我现在遇到了以下问题:
    猜你喜欢
    • 2018-10-01
    • 2023-03-25
    • 2021-11-22
    • 1970-01-01
    • 2016-11-16
    • 2018-03-05
    • 2021-03-23
    • 1970-01-01
    • 2019-12-13
    相关资源
    最近更新 更多