问题:检查Python列表项是否在另一个字符串中包含一个字符串
我有一个清单:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
并要搜索包含字符串的项目'abc'
。我怎样才能做到这一点?
if 'abc' in my_list:
会检查是否'abc'
存在在列表中,但它的一部分'abc-123'
和'abc-456'
,'abc'
对自己不存在。那么,如何获得包含的所有物品'abc'
?
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'
. 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. So how can I get all items that contain 'abc'
?
回答 0
如果您只想检查abc
列表中是否存在任何字符串,则可以尝试
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
# whatever
如果您确实要获取包含的所有项目abc
,请使用
matching = [s for s in some_list if "abc" in s]
If you only want to check for the presence of abc
in any string in the list, you could try
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
matching = [s for s in some_list if "abc" in s]
回答 1
只是丢掉它:如果您碰巧需要与多个字符串匹配,例如abc
和def
,则可以按如下方式组合两种理解:
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
输出:
['abc-123', 'def-456', 'abc-456']
Just throwing this out there: if you happen to need to match against more than one string, for example abc
and def
, you can combine two comprehensions as follows:
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
Output:
['abc-123', 'def-456', 'abc-456']
回答 2
使用filter
以获取该具备的要素abc
。
>>> lst = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> print filter(lambda x: 'abc' in x, lst)
['abc-123', 'abc-456']
您还可以使用列表推导。
>>> [x for x in lst if 'abc' in x]
顺便说一句,不要将单词list
用作变量名,因为它已经用于list
类型。
Use filter
to get at the elements that have abc
.
>>> lst = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> print filter(lambda x: 'abc' in x, lst)
['abc-123', 'abc-456']
You can also use a list comprehension.
>>> [x for x in lst if 'abc' in x]
By the way, don’t use the word list
as a variable name since it is already used for the list
type.
回答 3
如果您只想知道’abc’是否在其中一项中,这是最短的方法:
if 'abc' in str(my_list):
If you just need to know if ‘abc’ is in one of the items, this is the shortest way:
if 'abc' in str(my_list):
回答 4
这是一个很老的问题,但是我提供这个答案,因为先前的答案不能解决列表中不是字符串(或某种可迭代对象)的项。这些项目将导致整个列表理解失败,并发生异常。
要通过跳过不可迭代的项目来优雅地处理列表中的此类项目,请使用以下命令:
[el for el in lst if isinstance(el, collections.Iterable) and (st in el)]
然后,带有这样的列表:
lst = [None, 'abc-123', 'def-456', 'ghi-789', 'abc-456', 123]
st = 'abc'
您仍然会得到匹配的项目(['abc-123', 'abc-456']
)
可迭代的测试可能不是最好的。从这里得到它:在Python中,如何确定对象是否可迭代?
This is quite an old question, but I offer this answer because the previous answers do not cope with items in the list that are not strings (or some kind of iterable object). Such items would cause the entire list comprehension to fail with an exception.
To gracefully deal with such items in the list by skipping the non-iterable items, use the following:
[el for el in lst if isinstance(el, collections.Iterable) and (st in el)]
then, with such a list:
lst = [None, 'abc-123', 'def-456', 'ghi-789', 'abc-456', 123]
st = 'abc'
you will still get the matching items (['abc-123', 'abc-456']
)
The test for iterable may not be the best. Got it from here: In Python, how do I determine if an object is iterable?
回答 5
x = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]
x = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]
回答 6
for item in my_list:
if item.find("abc") != -1:
print item
for item in my_list:
if item.find("abc") != -1:
print item
回答 7
any('abc' in item for item in mylist)
any('abc' in item for item in mylist)
回答 8
使用__contains__()
Pythons字符串类的方法:
a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for i in a:
if i.__contains__("abc") :
print(i, " is containing")
Use the __contains__()
method of Pythons string class.:
a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for i in a:
if i.__contains__("abc") :
print(i, " is containing")
回答 9
我是Python的新手。我得到了下面的代码,使其易于理解:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for str in my_list:
if 'abc' in str:
print(str)
I am new to Python. I got the code below working and made it easy to understand:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for str in my_list:
if 'abc' in str:
print(str)
回答 10
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for item in my_list:
if (item.find('abc')) != -1:
print ('Found at ', item)
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for item in my_list:
if (item.find('abc')) != -1:
print ('Found at ', item)
回答 11
mylist=['abc','def','ghi','abc']
pattern=re.compile(r'abc')
pattern.findall(mylist)
mylist=['abc','def','ghi','abc']
pattern=re.compile(r'abc')
pattern.findall(mylist)
回答 12
我进行了搜索,要求您输入某个值,然后它将从包含您的输入的列表中查找一个值:
my_list = ['abc-123',
'def-456',
'ghi-789',
'abc-456'
]
imp = raw_input('Search item: ')
for items in my_list:
val = items
if any(imp in val for items in my_list):
print(items)
尝试搜索“ abc”。
I did a search, which requires you to input a certain value, then it will look for a value from the list which contains your input:
my_list = ['abc-123',
'def-456',
'ghi-789',
'abc-456'
]
imp = raw_input('Search item: ')
for items in my_list:
val = items
if any(imp in val for items in my_list):
print(items)
Try searching for ‘abc’.
回答 13
def find_dog(new_ls):
splt = new_ls.split()
if 'dog' in splt:
print("True")
else:
print('False')
find_dog("Is there a dog here?")
def find_dog(new_ls):
splt = new_ls.split()
if 'dog' in splt:
print("True")
else:
print('False')
find_dog("Is there a dog here?")
回答 14
我需要与匹配相对应的列表索引,如下所示:
lst=['abc-123', 'def-456', 'ghi-789', 'abc-456']
[n for n, x in enumerate(lst) if 'abc' in x]
输出
[0, 3]
I needed the list indices that correspond to a match as follows:
lst=['abc-123', 'def-456', 'ghi-789', 'abc-456']
[n for n, x in enumerate(lst) if 'abc' in x]
output
[0, 3]
回答 15
问题:提供abc的信息
a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
aa = [ string for string in a if "abc" in string]
print(aa)
Output => ['abc-123', 'abc-456']
Question : Give the informations of abc
a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
aa = [ string for string in a if "abc" in string]
print(aa)
Output => ['abc-123', 'abc-456']
回答 16
据我所知,“ for”陈述总是会浪费时间。
当列表长度增加时,执行时间也会增加。
我认为,使用“ is”语句在字符串中搜索子字符串会更快一些。
In [1]: t = ["abc_%s" % number for number in range(10000)]
In [2]: %timeit any("9999" in string for string in t)
1000 loops, best of 3: 420 µs per loop
In [3]: %timeit "9999" in ",".join(t)
10000 loops, best of 3: 103 µs per loop
但是,我同意该any
声明更具可读性。
From my knowledge, a ‘for’ statement will always consume time.
When the list length is growing up, the execution time will also grow.
I think that, searching a substring in a string with ‘is’ statement is a bit faster.
In [1]: t = ["abc_%s" % number for number in range(10000)]
In [2]: %timeit any("9999" in string for string in t)
1000 loops, best of 3: 420 µs per loop
In [3]: %timeit "9999" in ",".join(t)
10000 loops, best of 3: 103 µs per loop
But, I agree that the any
statement is more readable.