list的过滤操作

假设

l = ['abc', 'mn', 'aq', 'liuming']

我要过滤出以a开头的元素,方法有以下两种

方法1:

l = ['abc', 'mn', 'aq', 'liuming']
list1 = [e for e in l if e.startswith('a')]
print(list1)  #['abc', 'aq']

方法2:

def f(n):
    return  n.startswith('a')
 l = ['abc', 'mn', 'aq', 'liuming']
 r = filter(f, l)
 print(list(r)) #['abc', 'aq']

好了, 今天就get到这么点东西!

猜你喜欢

转载自www.cnblogs.com/z-qinfeng/p/11809425.html