在循环期间删除列表中的项

2024-04-26 12:13:03 发布

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

我有下面的代码。我试图从列表predict stringstest strings中删除两个字符串,如果在另一个列表中发现了其中一个。问题是,我必须将它们分开,并检查一个字符串中是否有另一个字符串中的“部分”。如果有,那么我只说有一个匹配,然后从列表中删除两个字符串,这样它们就不再重复。你知道吗

ValueError: list.remove(x): x not in list

但是我得到了上面的错误,我假设这是因为我不能从测试字符串中删除字符串,因为它正在被迭代?有办法吗?你知道吗

谢谢

    for test_string in test_strings[:]:
        for predict_string in predict_strings[:]:
            split_string = predict_string.split('/')
            for string in split_string:
                if (split_string in test_string):
                    no_matches = no_matches + 1
                    # Found match so remove both
                    test_strings.remove(test_string)
                    predict_strings.remove(predict_string)

输入示例:

test_strings = ['hello/there', 'what/is/up', 'yo/do/di/doodle', 'ding/dong/darn']
predict_strings =['hello/there/mister', 'interesting/what/that/is']

所以我希望在hello/there和hello/there/mister之间有一个匹配,并且在进行下一次比较时将它们从列表中删除。你知道吗

在一次迭代之后,我希望它是:

test_strings == ['what/is/up', 'yo/do/di/doodle', 'ding/dong/darn']
predict_strings == ['interesting/what/that/is']

在第二次迭代之后,我希望它是:

test_strings == ['yo/do/di/doodle', 'ding/dong/darn']
predict_strings == []

Tags: 字符串intesthello列表forstringis
2条回答

在迭代iterable时,千万不要试图修改它,这仍然是您试图做的有效操作。创建一个set来跟踪匹配项,然后在末尾删除这些元素。你知道吗

另外,你的台词for string in split_string:也没什么作用。您没有使用变量string。要么删除该循环,要么更改代码以便使用string。你知道吗

您可以使用增广赋值来增加no_matches的值。你知道吗

no_matches = 0

found_in_test = set()
found_in_predict = set()

for test_string in test_strings:
    test_set = set(test_string.split("/"))
    for predict_string in predict_strings:
        split_strings = set(predict_string.split("/"))
        if not split_strings.isdisjoint(test_set):
            no_matches += 1
            found_in_test.add(test_string)
            found_in_predict.add(predict_string)

for element in found_in_test:
    test_strings.remove(element)

for element in found_in_predict:
    predict_strings.remove(element)

从您的代码来看,两个split_string很可能匹配相同的test_string。第一次通过循环删除test_string,第二次尝试这样做,但是做不到,因为它已经被删除了!你知道吗

如果内部for循环找到匹配项,您可以尝试break从中退出,或者改用any。你知道吗

for test_string, predict_string in itertools.product(test_strings[:], predict_strings[:]):
    if any(s in test_string for s in predict_string.split('/')):
        no_matches += 1  # isn't this counter-intuitive?
        test_strings.remove(test_string)
        predict_strings.remove(predict_string)

相关问题 更多 >