python - 遍历不同长度的列表
问题描述
我正在尝试遍历 CSV 中的 4 列,每列都包含不同数量的销售 ID。我制作了一个熊猫数据框并将每一行转换为一个列表。如果一列的销售 ID 数量多于以下列,则会出现错误:
消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"/html/body/form[1]/div/select/option[@value=nan]"}
但是,如果所有列都具有相同数量的 id,则代码可以正常工作。
def get_report_data(self):
current_date = helpers.currentDate
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()
acq_ids = data['Acquisition'].tolist()
for form_code, sales_type, idlist in (
( 1, "Everyone", everyone_ids ),
( 1, "Daily Deal", dd_ids ),
( 2, "Targeted", targeted_ids ),
( 2, "Push Notification", push_ids ),
( 2, "Acquisition", acq_ids ) ):
print('Gathering {} Sale Information'.format(sales_type))
for sale_id in idlist:
results = []
helpers.WebDriverWait(helpers.driver, 10)
helpers.driver.find_element_by_xpath('/html/body/form[{}]/div/select/option[@value={}]'.format(form_code, sale_id)).click()
解决方案
内置函数any
可能与每个列表的pop
方法一起使用:
def get_report_data(self):
current_date = helpers.currentDate
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()
acq_ids = data['Acquisition'].tolist()
for form_code, sales_type, idlist in (
( 1, "Everyone", everyone_ids ),
( 1, "Daily Deal", dd_ids ),
( 2, "Targeted", targeted_ids ),
( 2, "Push Notification", push_ids ),
( 2, "Acquisition", acq_ids ) ):
print('Gathering {} Sale Information'.format(sales_type))
while any(idlist):
results = []
helpers.WebDriverWait(helpers.driver, 10)
helpers.driver.find_element_by_xpath(
'/html/body/form[{}]/div/select/option[@value={}]'.format(
form_code, idlist.pop(0)
)
).click()
推荐阅读
- mysql - 在 Spring Boot 应用程序启动之前带有事件调度程序的 MySQL 脚本
- css - 如何防止全局css选择器干扰Angular(6)中的孤立组件?
- elasticsearch - Kibana - 显示相对于其他图表结果的统计数据(百分比)
- java - Java/OpenCV - 如何在 openCV 中编写无损 h264 视频?
- google-sheets - 比较 Google 表格 QUERY() 公式中的日期
- webrtc - WebRTC/Mediarecorder 流到 FFMPEG JS
- python - Python Windows 原始套接字无效绑定参数
- c# - 如果矩形阵列速度较慢,那么它们比锯齿阵列有什么优势?
- android-things - JobService 未在 Android Things 上运行
- php - 使用 PHP/Laravel 加入/合并/组合 JSON 数据