gpt4 book ai didi

python - 如何对列表中的某些项目执行操作

转载 作者:太空宇宙 更新时间:2023-11-03 19:06:23 25 4
gpt4 key购买 nike

我有一些代码可以生成一定范围内(我们会说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次中显示空大括号。无需解释这种奇怪的现象,但解释一下我做错了什么以及我需要什么会有所帮助。谢谢。

最佳答案

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 xconditional expression如果整数在 [45, 55] 范围内,则减去 11。您也可以将其写为

x - 11 * (45 <= x <= 55)

由于TrueFalse具有数值 1 和 0。

关于python - 如何对列表中的某些项目执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14614377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com