Compare string with all values in array

前端 未结 4 743
小鲜肉
小鲜肉 2020-12-09 02:54

I am trying to fumble through python, and learn the best way to do things. I have a string where I am doing a compare with another string to see if there is a match:

4条回答
  •  旧时难觅i
    2020-12-09 03:32

    If you only want to know if any item of d is contained in paid[j], as you literally say:

    if any(x in paid[j] for x in d): ...
    

    If you also want to know which items of d are contained in paid[j]:

    contained = [x for x in d if x in paid[j]]
    

    contained will be an empty list if no items of d are contained in paid[j].

    There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d contained in paid[j] (and None if no item is so contained):

    firstone = next((x for x in d if x in paid[j]), None)
    

    BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in 'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j] into some more sophisticated predicate such as somere.search(paid[j]) for an appropriate RE object somere. (Python 2.6 or better -- slight differences in 2.5 and earlier).

    If your intention is something else again, such as getting one or all of the indices in d of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).

提交回复
热议问题