Background:
Example list: mylist = ['abc123', 'def456', 'ghi789']
I want to retrieve an element if there’s a match for a substring, like abc
Code:
sub = 'abc' print any(sub in mystring for mystring in mylist)
above prints True if any of the elements in the list contain the pattern.
I would like to print the element which matches the substring. So if I’m checking 'abc' I only want to print 'abc123' from list.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
print [s for s in list if sub in s]
If you want them separated by newlines:
print "n".join(s for s in list if sub in s)
Full example, with case insensitivity:
mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654'] sub = 'abc' print "n".join(s for s in mylist if sub.lower() in s.lower())
Method 2
All the answers work but they always traverse the whole list. If I understand your question, you only need the first match. So you don’t have to consider the rest of the list if you found your first match:
mylist = ['abc123', 'def456', 'ghi789'] sub = 'abc' next((s for s in mylist if sub in s), None) # returns 'abc123'
If the match is at the end of the list or for very small lists, it doesn’t make a difference, but consider this example:
import timeit
mylist = ['abc123'] + ['xyz123']*1000
sub = 'abc'
timeit.timeit('[s for s in mylist if sub in s]', setup='from __main__ import mylist, sub', number=100000)
# for me 7.949463844299316 with Python 2.7, 8.568840944994008 with Python 3.4
timeit.timeit('next((s for s in mylist if sub in s), None)', setup='from __main__ import mylist, sub', number=100000)
# for me 0.12696599960327148 with Python 2.7, 0.09955992100003641 with Python 3.4
Method 3
Use a simple for loop:
seq = ['abc123', 'def456', 'ghi789']
sub = 'abc'
for text in seq:
if sub in text:
print(text)
yields
abc123
Method 4
I’d just use a simple regex, you can do something like this
import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
print item
Method 5
This prints all elements that contain sub:
for s in filter (lambda x: sub in x, list): print (s)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0