我要匹配列表中的短语。
我正在使用python匹配列表中的短语。短语可以在列表中,也可以不在列表中。
line 10, in calculate
value_list = [value_a, value_b, value_c]
NameError: name 'value_a' is not defined
如果词组1和词组2在list1内,则返回正确或100%。目的是确保词组2和词组2逐字匹配。
相反,如果该短语不在列表内,或者仅一个短语位于列表2之内,则返回false或0%。
list1 = ['I would like to go to a party', 'I am sam', 'That is
correct', 'I am currently living in Texas']
phrase1= 'I would like to go to a party'
phrase2= 'I am sam'
可以更改短语,使其不仅可以与这两个短语不同。例如,可以将其更改为任何用户设置,例如“我不好”。
答案 0 :(得分:0)
似乎您只是想检查列表中的成员身份:
list1 = ['I would like to go to a party', 'I am sam', 'That is correct', 'I am currently living in Texas']
phrase1 = 'I would like to go to a party'
phrase2 = 'I am sam'
if phrase1 in list1 and phrase2 in list1:
# whatever you want, this will execute if True
pass
else:
# whatever you want, this will execute if False
pass
答案 1 :(得分:0)
我不确定我是否了解您,但我想也许您可以尝试
if phrase1 in list1
检查短语是否在列表中。
答案 2 :(得分:0)
您可以使用all和一个理解:
def check(phrase_list, *phrases):
return all(p in phrase_list for p in phrases)
使用中:
list1 = ['I would like to go to a party', 'I am sam', 'That is correct', 'I am currently living in Texas']
phrase1= 'I would like to go to a party'
phrase2= 'I am sam'
print(check(list1, phrase1, phrase2))
#True
print(check(list1, 'I am sam', 'dragon'))
#False
您也可以使用set
赞:
set(list1) >= {phrase1, phrase2}
#True
或者这样:
#you can call this the same way I called the other check
def check(phrase_list, *phrases):
return set(list1) >= set(phrases)
修改
要打印100%或0%,您可以简单地使用if语句或使用布尔索引:
print(('0%', '100%')[check(list1, phrases)])
要在您的return
语句中这样做:
return ('0%', '100%')[the_method_you_choose]