根据值划分列表

时间:2018-10-23 18:17:50

标签: 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],[2,7],[2,3],[3,8]]
]

在data [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]]
]

但是那并不能给我我想要的结果,感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

使用zip同时遍历多个列表。首先创建空的子列表,然后append创建这些列表:

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]]]