首页 > 解决方案 > python中for循环的问题只得到最后一项

问题描述

我是 python 的初学者,目前我正在尝试使用selenium.

我正在尝试使用循环遍历嵌套列表,for但总是只得到最后一个元素。任何建议为什么?

fields = [['a','b','c'],['x','y','z']]
for i in range(len(fields)):
    driver.find_element_by_xpath("element").send_keys(fields[i][0],fields[i[1],fields[i][2])
    driver.find_element_by_xpath("element_save").click()

#then loop and iterate through 2nd nested list

# OUTPUT = x,y,z

我希望从索引 0 开始迭代到列表的末尾。

标签: pythonloopsfor-loopiterationenumerate

解决方案


您不需要range(len(list_))仅迭代索引。

通常for会做。您还可以使用以下命令解压缩列表*

fields = [['a','b','c'],['x','y','z']]
len_ = len(fields)
for i in range(len_):
    driver.find_element_by_xpath("element").send_keys(*fields[i])

您还可以遍历自身的值fields

fields = [['a','b','c'],['x','y','z']]

for field in fields:
    driver.find_element_by_xpath("element").send_keys(*field)

推荐阅读