Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.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/8/python-3.x/15.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,我有三个列表,如下所示: a = [0,0,0,0,0,1,1,1,1,1,2,2,2,2] b = [1,2,3,5,6,7,7,4,3,2,1,2,2,3] c = [3,4,5,2,5,7,8,2,1,3,4,7,3,8] 我想将[b,c]附加到一个新列表的相应索引中,其中a是索引,以澄清我的意思,这是期望的结果 data = [ [[1,3],[2,4],[3,5],[5,2],[6,5]], [[7,7],[7,8],[4,2],[3,1],[2,3]], [[1,4],

我有三个列表,如下所示:

a = [0,0,0,0,0,1,1,1,1,1,2,2,2,2]
b = [1,2,3,5,6,7,7,4,3,2,1,2,2,3]
c = [3,4,5,2,5,7,8,2,1,3,4,7,3,8]
我想将[b,c]附加到一个新列表的相应索引中,其中a是索引,以澄清我的意思,这是期望的结果

data = [
  [[1,3],[2,4],[3,5],[5,2],[6,5]],
  [[7,7],[7,8],[4,2],[3,1],[2,3]],
  [[1,4],[2,7],[2,3],[3,8]]
]
如在数据[0]=[b,c]中,a是0,依此类推

我试图用以下代码实现这一点

n = list(set(a))
data= [[]]*len(n)
cnt = 0

for i in range(len(a)-1):
    if a[i] == a[i+1] and a[i] == cnt:
        data[cnt].append([b[i],c[i]])
    if a[i] != a[i+1] and a[i] == cnt:
        data[cnt].append([b[i],c[i]])
        cnt += 1
这给了我一个答案:

data = [
  [[1, 3], [2, 4], [3, 5], [5, 2], [6, 5], [7, 7], [7, 8], [4, 2], [3, 1], [2, 3], [1, 4], [2, 7], [2, 3]], 
  [[1, 3], [2, 4], [3, 5], [5, 2], [6, 5], [7, 7], [7, 8], [4, 2], [3, 1], [2, 3], [1, 4], [2, 7], [2, 3]], 
  [[1, 3], [2, 4], [3, 5], [5, 2], [6, 5], [7, 7], [7, 8], [4, 2], [3, 1], [2, 3], [1, 4], [2, 7], [2, 3]]
]

但这并没有给我想要的结果,任何帮助都是感激的

使用
zip
同时迭代多个列表。最初创建空的子列表,然后
将其追加到这些列表中:

A = [0,0,0,0,0,1,1,1,1,1,2,2,2,2]
B = [1,2,3,5,6,7,7,4,3,2,1,2,2,3]
C = [3,4,5,2,5,7,8,2,1,3,4,7,3,8]

lst = [[] for _ in range(max(A) + 1)]

for a, b, c in zip(A, B, C):
    lst[a].append([b, c])

print(lst)
# [[[1, 3], [2, 4], [3, 5], [5, 2], [6, 5]], [[7, 7], [7, 8], [4, 2], [3, 1], [2, 3]], [[1, 4], [2, 7], [2, 3], [3, 8]]]

这给你的结果有什么问题?
c[i],c[i]
是最后一行的打字错误吗?您是否总是缺少最终数组中的最后一个元素?我将更新问题,显示使用上述代码得到的结果。是的,我错过了一个我不知道如何修复的元素,我的迭代器不好,我猜
lst[a]
是一个聪明而酷的技巧