标签:元素 lang present blog log python 转换 示例 loading
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.
array_diff([1,2],[1]) == [2]
array_diff([1,2,2,2,3],[2]) == [1,3]
my code
def array_diff(a, b):
for num in b:
while num in a:
a.remove(num)
return a
others‘ code
def array_diff(a, b):
return [x for x in a if x not in b]
def array_diff(a, b):
return [x for x in a if x not in set(b)]
def array_diff(a, b):
#your code here
return filter(lambda i: i not in b, a)
set()
具有去重功能
列表推导式
list
& dict
& set
的时间复杂度
filter(function,iterable)
用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用list()
来转换
fliter使用示例
#过滤出列表中的奇数
def is_odd(n):
return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
#过滤出1~100内的平方数
import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)
备注:部分内容参考这个博客,仅供学习交流使用,侵删。
标签:元素 lang present blog log python 转换 示例 loading
原文地址:https://www.cnblogs.com/zjx-pku/p/13174177.html