Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表中的内部分组_Python_Python 3.x_List - Fatal编程技术网

Python 列表中的内部分组

Python 列表中的内部分组,python,python-3.x,list,Python,Python 3.x,List,我在python中工作。上面的代码是用来将相邻的正片组合在一起的。我认为这个问题会吸引其他人,因为我收到了错误。那会是什么错误呢?索引器 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中工作。上面的代码是用来将相邻的正片组合在一起的。我认为这个问题会吸引其他人,因为我收到了错误。那会是什么错误呢?索引器

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]
我试图实现的是将如下所示的列表分组:[[1]、[2]、[3]、-4]、-3]、-2]、-1]、[0]]
类似于这样的内容:[[1,2,3],-4,-3,-2,-1],[0]]我没有其他导入,这不会调用任何其他函数。我该怎么做,为什么我会收到这个错误?我的理论是,它存在于RangeLenip中,但我已经尝试了很多次,但没有成功。每个数字周围的括号都是有意的,因此我可以通过添加数字将其组合到列表中。如果你有不同的方法,请告诉我。我希望这是关于一般的内部分组,因此尝试概括一下我在这方面的错误。

以下是使用itertools的方法:

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

如果你认为0是自己的类,你可以通过替换lambda x:x:这是一个机器学习库,并把正合在一起是我的过程中的一个重要步骤。我希望我能解释一下原因,但那将是一个很长的注释。您正在删除一个列表元素,同时对其进行迭代。不要这样做。如果您有一个列表[[1]、-1]、[1]],您会喜欢它的现状吗?假设0为正数吗?标准itertools模块有一个groupby函数,适用于此类任务。您还应该显示一个使用平面列表的简单版本。OP仅使用列表列表来简化合并组的任务。您可以使用来避免解压缩列表。我删除了更复杂的版本。为什么不将0分组为正数?在lambda check上都返回False..@Ev.Kounis负数小于0,因此返回True

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]]
>>> gp_new([1, 2, 3, -4, -3, -2, -1, 0, 1, 2, 3])
[[1, 2, 3], [-4, -3, -2, -1], [0], [1, 2, 3]]