我有一个名为category的列表,它有以下值
`category=['Constant', 'Constant', 'Constant', 'Constant', 'Categorical', 'Categorical', 'Categorical', 'Categorical', 'Categorical', 'Constant', 'Constant', 'Categorical', 'Constant', 'Categorical', 'Categorical', 'Categorical', 'Categorical', 'Categorical', 'Constant', 'Categorical', 'Categorical', 'Categorical']`
我必须浏览这个列表,创建一个新列表,并在值为“常量”的地方插入名为“无”的值。但在我的例子中,我只能在开头插入'None'(对于前4个值),不能在列表中间插入'None'。(例如:我想在第10位、第11位、第13位打印“无”)。你能看看我的代码,告诉我我犯了什么错误吗
distinct = []
for x in category:
if x == 'Constant':
distinct.append('None')
elif x == 'Categorical':
distinctvalue = driver.find_elements_by_xpath("My XPath has list of items")
for dv in distinctvalue:
distval = dv.text
distinct.append(distval)
break
print(distinct)
O/p:我有['None', 'None', 'None', 'None', '1027', '1117', '2', '1117', '1027', '2', '2', '26', '2', '363', '96', '363', '339545', '96']
预期O/p:['None', 'None', 'None', 'None', '1027', '1117', '2', '1117', '1027','None','None', '2', 'None', '2', '26', '2', '363', '96','None', '363', '339545', '96']
从代码的elif块中删除“break”
不要试图在
elif
中完成整个循环,而是在需要时从列表中获取下一个值有两种方法可以做到这一点:
按列表索引。
使用索引变量(此处
i
)跟踪您在列表中到达的位置:如果您可能提前用完了不同的值,那么您可以为此设置一个捕获,这样,如果它尝试获取下一个值,但没有,那么它将从循环中
break
替换:与:
使用迭代器。
这次我们使用
iter
从列表中生成一个迭代器,并使用next
从该迭代器中获取下一个值:这一次,要在值用完时尽早退出循环,您需要替换:
与:
相关问题 更多 >
编程相关推荐