我有下面的代码。我试图从列表predict strings
和test 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 == []
在迭代iterable时,千万不要试图修改它,这仍然是您试图做的有效操作。创建一个
set
来跟踪匹配项,然后在末尾删除这些元素。你知道吗另外,你的台词
for string in split_string:
也没什么作用。您没有使用变量string
。要么删除该循环,要么更改代码以便使用string
。你知道吗您可以使用增广赋值来增加
no_matches
的值。你知道吗从您的代码来看,两个
split_string
很可能匹配相同的test_string
。第一次通过循环删除test_string
,第二次尝试这样做,但是做不到,因为它已经被删除了!你知道吗如果内部
for
循环找到匹配项,您可以尝试break
从中退出,或者改用any
。你知道吗相关问题 更多 >
编程相关推荐