这是一个字符串列表。
'"5" is a magic number.'
'"6" is a magic number.'
'"7" is a magic number.'
'This line is extra...'
'This line is extra...'
'"8" is a magic number.'
在python中挑选出像“**是一个神奇的数字”这样的最有效方法是什么?
使用列表推导:
mylist = ['"5" is a magic number.', ..., '"8" is a magic number.']
print [i for i in mylist if "is a magic number" in i]
印刷:
['"5" is a magic number.', '"6" is a magic number.', '"7" is a magic number.', '"8" is a magic number.']
使用 re.findall 的正则表达式解决方案:
import re
mylist = ['"5" is a magic number.',
'"6" is a magic number.',
'"7" is a magic number.',
'This line is extra...',
'This line is extra...',
'"8" is a magic number.']
print re.findall(r'"\d+" is a magic number', ' '.join(mylist))
假设您有一个未排序的字符串块,正如您所描述的:
strs='''\
"17" is a magic number.
"6" is a magic number.
"5" is a magic number.
This line is extra...
This line is extra...
"8" is a magic number.'''
现在你想解析和排序字符串中的数字:
import re
out=sorted([s for s in strs.splitlines() if s.endswith('is a magic number.')],
key=lambda r: int(re.match(r"[\D]*(\d+)",r).group(1)))
print '\n'.join(out)
印刷:
"5" is a magic number.
"6" is a magic number.
"8" is a magic number.
"17" is a magic number.
像这样的东西?
my_strings = ['"5" is a magic number.',
'"6" is a magic number.',
'"7" is a magic number.',
'This line is extra...',
'This line is extra...',
'"8" is a magic number.']
print filter(lambda elem: 'magic number' in elem, my_strings)
或使用正则表达式:
import re
p = re.compile("'[0-9]+' is a magic number", re.IGNORECASE)
print filter(lambda elem: bool(p.match(elem)), my_strings)
# if it doesn't match, it returns None which is False