Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_List Comprehension - Fatal编程技术网

Python 在列表列表中获取对

Python 在列表列表中获取对,python,list,list-comprehension,Python,List,List Comprehension,我需要你的帮助,我希望你能给我指出正确的方向,所以我得到了一个列表(这只是一个例子,列表可以有更多的元素),我试图得到列表中的元素对 mylist = [[2, 3, 4], [2, 3]] #desired output # newlist = [[2,3], [3,4], [2,3]] 在这里,它有助于创建一个元组列表,其中每个元组都是一对,所以我使用这个问题的答案来创建这个代码 mylist = [[2, 3, 4], [2, 3]] coordinates = [] for i

我需要你的帮助,我希望你能给我指出正确的方向,所以我得到了一个列表(这只是一个例子,列表可以有更多的元素),我试图得到列表中的元素对

mylist = [[2, 3, 4], [2, 3]]

#desired output
# newlist = [[2,3], [3,4], [2,3]]
在这里,它有助于创建一个元组列表,其中每个元组都是一对,所以我使用这个问题的答案来创建这个代码

mylist = [[2, 3, 4], [2, 3]]

coordinates = []

for i in mylist:
    coordinates.append(list(map(list, zip(i, i[1:])))) #Instead of list of tuples, I use map to get a list of lists

print(coordinates)
#output [[[2, 3], [3, 4]], [[2, 3]]] #3D list  but not exactly what I want

a = [e for sl in coordinates for e in sl] #Use list comprehension to transform the 3D list to 2D list

print(a)
#output [[2, 3], [3, 4], [2, 3]] #My desired output

使用这段代码,我得到了我想要的,但我想知道是否有一种简单的方法可以实现这一点,而不需要创建一堆辅助列表,也许需要一个简单的列表理解?但是我不知道怎么做,所以任何帮助都将不胜感激,谢谢

您可以使用嵌套列表:

mylist = [[2, 3, 4], [2, 3]]
def get_groups(l, n):
  return [l[i:i+n] for i in range(len(l)-n+1)]

new_l = [i for b in mylist for i in get_groups(b, 2)]
输出:

[[2, 3], [3, 4], [2, 3]]
试试这个:

mylist = [[3, 2, 4, 3], [3, 3, 1], [2, 1]]
res = [x[idx: idx+2] for x in mylist for idx in range(0, len(x) - 1)]
print(res)
输出:

[[3, 2], [2, 4], [4, 3], [3, 3], [3, 1], [2, 1]]

我的列表总是只包含两个列表吗?不一定,我的列表可以是mylist=[[3,2,4,3],[3,3,1],[2,1]],并且输出应该是newlist=[[3,2],[2,4],[4,3],[3,3],[3,1],[2,1]]为什么不直接使用
extend(…)
而不是
append(list(…)