我有一些代码,可以在一定范围内生成随机数列表(我们会说0-100),但我希望出现在范围(45-55)内的数字不会出现。
为了我的特定目的,,我想知道如何将11加/减到这个范围内的数字中。我写了一句话:
desired_list = [integer_list[i] - 11 for i in range(len(integer_list)) if integer_list[i] in list_of_consecutive_unwanted_integers]但是现在,当我打印desired_list时,它显示空大括号大约4/5次,我检索了随机数。没有必要解释这个奇怪的现象,但解释我做错了什么和我需要什么将是有帮助的。谢谢。
发布于 2013-01-30 21:50:31
integer_list[i] in list_of_consecutive_unwanted_integers检查整数是否是不需要的,丢弃“不想要的列表”中没有的,并保留不想要的。
下面是我解决这个问题的方法:
>>> # let's get 20 random integers in [0, 100]
>>> random_integers = (randint(0, 100) for _ in xrange(20))
>>> [x - 11 if 45 <= x <= 55 else x for x in random_integers]
[62, 0, 28, 34, 36, 96, 20, 19, 84, 17, 85, 83, 17, 91, 98, 33, 5, 100, 94, 97]x - 11 if 45 <= x <= 55 else x是一个条件表达式,如果整数在45,55范围内,它减去11。你也可以把它写成
x - 11 * (45 <= x <= 55)因为True和False有数值1和0。
发布于 2013-01-30 22:27:46
>>> l # Let l be the list of numbers in the range(0, 100) with some elements
[3, 4, 5, 45, 48, 6, 55, 56, 60]
>>> filter(lambda x: x < 45 or x > 55, l) # Remove elements in the range [45, 55]
[3, 4, 5, 6, 56, 60]filter将函数f应用于输入序列,并返回f(item)返回True的序列的项。
滤波器(.) 筛选(函数或无,序列) ->列表、元组或字符串 返回函数(项)为真的序列项。如果函数为None,则返回为true的项。如果序列是元组或字符串,则返回相同的类型,否则返回列表。
https://stackoverflow.com/questions/14614377
复制相似问题