简体   繁体   English

如何对行进行重新编码,以便准确的句子必须在列表中才能匹配

[英]How to recode line so an exact sentence must be in the list for it to match

x = ["Cookie flavored water is yummy 6", "Coding complicated 16", "Help 7"]

for i in x:
    if "flavored" in x:
        print ("Yes")
    else:
        print ("No")

I want the exact string "Cookie flavored water is yummy" to be in the list for it to be acceptable but I don't want the 6 part included. 我希望确切的字符串“ Cookie味的水很好吃”在列表中,这样它可以被接受,但是我不希望包含6部分。 I'm completely befuddled on how to accomplish this. 我完全迷住了如何做到这一点。 Also the objective might change from the first element to a different element. 同样,目标可能会从第一个元素变为另一个元素。

Well if the string is always the one you specified you could do this: 好吧,如果字符串始终是您指定的字符串,则可以执行以下操作:

yourString = "Cookie flavored water is yummy"
for item in x:
    if yourString in item:
        print 'Yes'
    else:
        print 'No'

This check each list item for the specified string. 这会检查每个列表项是否包含指定的字符串。 In your example "Cookie flavored water is yummy 6" contains the substring "Cookie flavored water is yummy". 在您的示例中,“ Cookie调味的水很好吃”包含子字符串“ Cookie调味的水很好吃”。 So the script will print 'Yes' 因此脚本将显示“是”

you're iterating on x with i but you check if string belongs to the list, not the element, which is always false. 您正在使用ix进行迭代,但是您检查string是否属于列表,而不是属于列表,该列表始终为false。

to check if an element of x contains "Cookie flavored water is yummy" 检查x的元素是否包含"Cookie flavored water is yummy"

x = ["Cookie flavored water is yummy 6", "Coding complicated 16", "Help 7"]

for i in x:
    print ("Yes" if "Cookie flavored water is yummy" in i else "No")

on the other hand, for exact string match simply use in without a loop, the loop being made on x by the in operator: 另一方面,对于精确的字符串匹配,只需in不带循环的情况下使用in ,该循环由in运算符在x进行:

print ("Yes" if "Cookie flavored water is yummy" in x else "No")

If you need exact string match on a great number of elements, consider putting your elements in a set instead because lookup time is much smaller (hashing involved). 如果您需要对大量元素进行精确的字符串匹配,请考虑将元素放在set因为查找时间要短得多(涉及散列)。 The code remains the same apart from that. 除此之外,代码保持不变。

What do you mean by "acceptable?" “可接受”是什么意思? Additionally, when you say you don't want the number at the end of the items in the list to be included, do you mean for your comparison? 此外,当您说不想包含列表中项目末尾的数字时,是要进行比较吗? I agree with the other answers, and if you happen to want to remove the numbers from the list: 我同意其他答案,如果您碰巧想从列表中删除数字,请执行以下操作:

x = [' '.join(i.split(' ')[:-1]) for i in x]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM