gpt4 book ai didi

python - 列表中的内部分组

转载 作者:行者123 更新时间:2023-11-28 22:21:31 25 4
gpt4 key购买 nike

def gp(inp): #group positives in the list
for x in range(len(inp)-1):
if is_pos(inp[x][0]) and is_pos(inp[x+1][0]):
inp[x] += inp[x+1]
del inp[x+1]

我在 python 工作。上面的代码用于将相邻的正例分组在一起。我认为这个问题会因为我收到的错误而吸引其他人。那个错误是什么?一个索引错误。

Traceback (most recent call last):
File "python", line 95, in <module>
File "python", line 49, in formt
File "python", line 10, in gp
IndexError: list index out of range

我想要实现的是对如下所示的列表进行分组:[[1],[2],[3],[-4],[-3],[-2], [-1],[0]]看起来像这样:[[1,2,3],[-4,-3,-2,-1],[0]] 我没有其他导入,这也没有不要调用任何其他函数。我将如何着手执行此操作,为什么会收到该错误?我的理论是它位于 range(len(inp)) 中,但我已经尝试了很多,但没有成功。每个单独数字周围的括号是有意的,因此我可以通过“添加”它们将数字组合到列表中。如果你有不同的方法,请告诉我。我希望这是关于一般内部分组的,所以请尝试概括我做错了什么。

最佳答案

以下是使用 itertools 的方法:

from itertools import groupby

def gp(inp):
return [
list(things) # groupby yields iterators
for _, things # throw away the truth value
# chain to remove the nesting
in groupby(inp, lambda x: x<0)
]

用法:

>>> gp([1, 2, 3, -4, -3, -2, -1, 0])
[[1, 2, 3], [-4, -3, -2, -1], [0]]

如果您将 0 视为自己的类,则可以通过替换 lambda x: x<0 来避免一些麻烦。与 lambda x: x*float("inf") :

>>> gp_new([1, 2, 3, -4, -3, -2, -1, 0, 1, 2, 3])
[[1, 2, 3], [-4, -3, -2, -1], [0], [1, 2, 3]]

关于python - 列表中的内部分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48323679/

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