python takes list and returns only if negative value also exists using set(python获取列表并仅在使用set也存在负值时才返回)
问题描述
基本上我有一个很大的清单:
Basically I have a big list:
# where (n) is over a couple hundred thousand or is 1 million
def big_list(n):
return [ randrange(-n//3,n//3) for i in range(n) ]
并且使用 set
当且仅当它的负值也存在时,我必须返回一个新列表.
And using a set
I must return a new list if and only if its negative value also exists.
例如.如果 list = [-3,-2,-1,2,1,4]
它应该返回 new_list = [2,1]
Ex. if list = [-3,-2,-1,2,1,4]
it should return new_list = [2,1]
我必须使用 set
来完成这项工作,我真的迷路了.
I must do this using set
, and I''m really lost.
推荐答案
如果您从使用 big_list()
创建的列表中创建 set
,则可以使用它来通过遍历集合的所有元素并选择所有值大于 0 且负值也在集合中的元素来创建所需的结果列表.
If you create a set
from a list created with big_list()
, you can use it to create a desired result list by iterating through all the elements of the set and selecting all those whose values are > 0 and whose negative value is also in the set.
您可以使用列表显示表达式,通常称为列表推导式",用于在 []
括号内创建带有一行长代码的结果列表,就像 big_list()
函数一样.
You can use a list display expression, commonly call a "list comprehension", to create the resultant list with one long-ish line of code inside []
brackets, like the big_list()
function does.
希望这会有所帮助.
这篇关于python获取列表并仅在使用set也存在负值时才返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python获取列表并仅在使用set也存在负值时才返回


基础教程推荐
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01