根据特定条件在列表中间插入值

2024-09-28 22:31:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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']


Tags: innone列表for地方例子常量category
2条回答

从代码的elif块中删除“break”

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 # remove this

不要试图在elif中完成整个循环,而是在需要时从列表中获取下一个值

有两种方法可以做到这一点:

按列表索引。

使用索引变量(此处i)跟踪您在列表中到达的位置:

distinct = []
distinctvalue = driver.find_elements_by_xpath("My XPath has list of items")

i = 0  # <== initialise the index variable
for x in category:
    if x == 'Constant':
        distinct.append('None')
    elif x == 'Categorical':
        dv = distinctvalue[i]  # <== use the index variable to look up next value
        i += 1  # <== increment the counter ready for next time
        distval = dv.text
        distinct.append(distval)
print(distinct)

如果您可能提前用完了不同的值,那么您可以为此设置一个捕获,这样,如果它尝试获取下一个值,但没有,那么它将从循环中break替换:

        dv = distinctvalue[i]

与:

        try:
            dv = distinctvalue[i]
        except IndexError:
            break

使用迭代器。

这次我们使用iter从列表中生成一个迭代器,并使用next从该迭代器中获取下一个值:

distinct = []
distinctvalue = iter(driver.find_elements_by_xpath("My XPath has list of items"))  # <== get the iterator

for x in category:
    if x == 'Constant':
        distinct.append('None')
    elif x == 'Categorical':
        dv = next(distinctvalue)  # <== next one
        distval = dv.text
        distinct.append(distval)
print(distinct)

这一次,要在值用完时尽早退出循环,您需要替换:

        dv = next(distinctvalue)

与:

        try:
            dv = next(distinctvalue)
        except StopIteration:
            break

相关问题 更多 >