文章预览
严格来说,本文的2个代码不算花式编程,在Python中就应该是这样写。 1、生成包含20个随机数的列表,然后删除其中的所有奇数。 from random import randrange lst = [randrange(10) for _ in range (20)] print (lst) lst = list ( filter ( lambda x: x%2==0, lst)) print (lst) 某次运行结果为: [6, 3, 9, 6, 6, 7, 5, 3, 4, 0, 6, 6, 5, 9, 4, 7, 3, 8, 6, 4] [6, 6, 6, 4, 0, 6, 6, 4, 8, 6, 4] 2、生成包含20个随机数的列表,然后将偶数位置上的元素降序排列,奇数位置上的元素不变。 from random import randrange lst = [randrange(10) for _ in range (20)] print (lst) lst[::2] = sorted (lst[::2], reverse= True ) print (lst) 某次运行结果为: [0, 5, 4, 6, 1, 3, 5, 1, 2, 9, 7, 3, 9, 1, 8, 4, 1, 2, 3, 3] [9, 5, 8, 6, 7, 3, 5, 1, 4, 9, 3, 3, 2, 1, 1, 4, 1, 2, 0, 3] --------我是分割线--
………………………………