出于某种原因,我的大脑不能正常工作。
我有两个排序的类似列表的对象:
>>> a = [1,2,3,4]
>>> b = [1,1,2,2,2,3,3,3]
由此,我需要得到:
>>> a = [ [1,[1,1]], [2,[2,2,2]], [3,[3,3,3]], 4]
Codewise,我在想这个......
>>> i = 0
>>> first = True
>>> for num in b:
... if num == a[i]:
... if first:
... a[i] = [a[i],[num]]
... first = False
... else:
... a[i][1].append(num)
... else:
... first = True
... if a[i+1] == num:
... a[i] = [a[i+1],[num]]
... else:
... print 'problem'
但我一直感到困惑。什么是解决这个问题的有效方法?也许,我感觉像是递归,但我也无法解决这个问题。
答案 0 :(得分:6)
由于数据已经排序,您可以根据数字对b
进行分组,并使用字典理解创建字典。在下一次通过键(a
)时,您可以从字典中获取与a
元素对应的元素,并创建一个新列表。
a, b = [1,2,3,4], [1,1,2,2,2,3,3,3]
from itertools import groupby
d = {k:list(grp) for k, grp in groupby(b)}
# {1: [1, 1], 2: [2, 2, 2], 3: [3, 3, 3]}
print [[k, d[k]] if k in d else k for k in a]
# [[1, [1, 1]], [2, [2, 2, 2]], [3, [3, 3, 3]], 4]
答案 1 :(得分:2)
我会这样做:
from collections import Counter
a = [1,2,3,4]
b = [1,1,2,2,2,3,3,3]
bb = Counter(b)
new_list = [[el_a,[el_a for _ in range(bb[el_a])]] for el_a in a]
# [[1, [1, 1]], [2, [2, 2, 2]], [3, [3, 3, 3]], [4, []]]
答案 2 :(得分:0)
易读选项:
finallist = []
a = [1,2,3,4]
b = [1,1,2,2,2,3,3,3]
pos = 0
for item in a:
mylist = [item,[]]
while pos < len(b) and b[pos] == item :
mylist[1].append(item)
pos += 1
finallist.append(mylist)
print finallist