对一个含正数负数列表统计及排序的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Jerry_1126/article/details/85239946

有一道Python面试题:已知列表,foo = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]

1). 求列表中整数,负数元素各多少个? 里面如有重复元素,只算一个,比如,里面有两个8,只算一个

# 方法一: 先用filter过滤负数,再在set(foo)中取正数
>>> len(filter(lambda x:x>0, set(foo)))
4
>>> len(filter(lambda x:x<0, set(foo)))
4

# 方法二:int(x>0)的话为1,这是巧妙之处
>>> sum([int(x>0) for x in set(foo)])
4
>>> sum([int(x<0) for x in set(foo)])
4

# 方法三:列表推导的常用做法
>>> foo = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]
>>> len([i for i in set(foo) if i > 0])
4
>>> len([i for i in set(foo) if i < 0])
4


2). 使用lambda函数对列表foo排序,输出结果为[0,2,4,8,8,9,-2,-4,-4,-5,-20],正数从小到大,负数从大到小

# 方法一:
>>> foo = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]
>>> sorted(filter(lambda x:x>0, foo)) + sorted(filter(lambda x:x<0,foo), reverse=True)
[2, 4, 8, 8, 9, -2, -4, -4, -5, -20]

# 方法二:
>>> foo = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]
>>> sorted(filter(lambda x:x>0, foo)) + sorted(filter(lambda x:x<0,foo))[::-1]
[2, 4, 8, 8, 9, -2, -4, -4, -5, -20]

# 方法三:
>>> foo = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]
>>> sorted(foo, key=lambda x:(x<0, abs(x)))
[0, 2, 4, 8, 8, 9, -2, -4, -4, -5, -20]

# 方法四:
>>> foo = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]
>>> sorted(foo, key=lambda x:(int(x<0), abs(x)))
[0, 2, 4, 8, 8, 9, -2, -4, -4, -5, -20]

猜你喜欢

转载自blog.csdn.net/Jerry_1126/article/details/85239946
今日推荐