【发布时间】:2016-09-21 19:13:58
【问题描述】:
我有一个这样的列表:
edu_options = { 'Completed Graduate School' : ['medical','litigation','specialist'...],
'Completed College' : ['linguistic','lpn','liberal','chicano'... ],
'Attended College' : ['general','inprogress','courseworktowards','continu'...],
我的原始代码没有尝试分层匹配:
for edu_level in edu_options:
for option in edu_options[edu_level]
if option in cleaned_string:
user = edu_level
return user
else: continue
我正在将一个字符串与这些列表进行比较并返回密钥。我想以分层的方式来做。
for edu_level in edu_options:
for option in edu_options[edu_level]:
if cleaned_string in edu_options["Completed Graduate School"]:
user = "Completed Graduate School"
return user
elif cleaned_string in edu_options["Completed College"]:
user = "Completed College"
return user
elif option in cleaned_string:
user = edu_level
return user
这些 if 语句适用于大多数比较 str 但不适用于少数情况。对于第一个和第二个 if 语句,我只想将其与相应的列表进行比较,例如“完成研究生院”。有没有办法只遍历那个列表而不使用另一个 for 循环?像
Ex: string = Bachelor of Arts: Communication and Civil Service
cleaned_string = bachelorofartscommunicationandcivilservice
option = iterating through each item(str) of lists in edu_option
我希望首先列出毕业生和大学名单,因为它们更小、更具体。我要纠正的错误是 edu_options 中另一个较大的列表包含不正确地匹配到 clean_string 的 sub str。
【问题讨论】:
-
cleaned_string 是一个列表吗?还是在 cleanded_string 中查找子字符串?
-
cleaned_string 只是一个 str,我想与 edu_options 列表中的 strs 进行比较
-
因此,当您说“cleaned_string 中的elif 选项”时,将在cleaned_string(也是一个字符串)中查找作为字符串的选项。这是你打算做的吗?
-
一个例子:elif Bachelor(option) in Bachelorofscience(cleaned_string): user = edu_level (来自任何列表选项)
-
我完全看不懂这段代码。
if和第一个elif不检查任何循环变量,因此您可以将它们放在循环之前并获得相同的结果。而且他们似乎没有做任何与上一个elif有明显不同的事情,所以在我看来他们可以简单地被删除。 (唯一真正的区别是它们进行完全匹配而不是子字符串匹配。由于较松散的子字符串匹配发生在循环的后面,因此您仍然会得到相同的结果。)
标签: python list dictionary