Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

python - 检查Python列表项是否在另一个字符串中包含一个字符串(Check if a Python list item contains a string inside another string)

I have a list:

(我有一个清单:)

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

and want to search for items that contain the string 'abc' .

(并要搜索包含字符串'abc' 。)

How can I do that?

(我怎样才能做到这一点?)

if 'abc' in my_list:

would check if 'abc' exists in the list but it is a part of 'abc-123' and 'abc-456' , 'abc' does not exist on its own.

(会检查列表中是否存在'abc' ,但它是'abc-123''abc-456' ,因此'abc'不存在。)

So how can I get all items that contain 'abc' ?

(那么,如何获取所有包含'abc' ?)

  ask by SandyBr translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you only want to check for the presence of abc in any string in the list, you could try

(如果您只想检查列表中任何字符串中是否存在abc ,可以尝试)

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
    # whatever

If you really want to get all the items containing abc , use

(如果您真的想获取所有包含abc的项目,请使用)

matching = [s for s in some_list if "abc" in s]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...