我有两个列表:
a = [0,0,2,2,2,2]
b = [1,3,2,3,6,7]
A和b相互关联,与b[i]
相关的a[i]
,我想得到
c = [[0,1,3],[2,2,3],[2,6,7]]
当a
= 0
时,b
中有2个值与0
对应,即b[0],b[1]
,因此将它们连接起来作为c
的第一个内核表,
当a
=2
时,有4个值与2
相关,即b[2],b[3],b[4],b[5]
,但b[3]
和b[4]
之间的差距大于3
,因此c[2]
以[2,2,3]
身份停止并创建连接<代码>D19和<代码>D20的新列表
所以我的标准是,当两个b[i],b[i+1]....
都与a
的特定值相关,但是它们有一个间隙,也就是>= 3
,首先创建一个列表[a[i],b[i]]
,然后再合并其他的。我被它卡住了。
发布于 2019-03-12 09:55:24
首先,根据a
创建组
c = zip(a, b)
c = {k: [bi for ai, bi in g] for k, g in groupby(c, lambda i: i[0])}
现在连接到一个列表列表(按顺序):
c = [v for k, v in sorted(c.items())]
现在,您需要一个按值差距拆分的函数:
def split_max_gap(l, max_gap=2):
acc = [l[0]]
for x, y in zip(l, l[1:]):
if abs(x - y) > max_gap:
yield acc
acc = [y]
continue
acc.append(y)
if acc:
yield acc
将拆分应用于上一个列表列表:
c = map(split_max_gap, c)
展平:
c = list(chain.from_iterable(c))
c
现在应该保持:
[[1, 3], [2, 3], [6, 7]]
发布于 2019-03-12 13:23:33
你写了
b3和b4之间的差距大于3
但它并不是更大。它是更大或相等的。
a = [0, 0, 2, 2, 2, 2]
b = [1, 3, 2, 3, 6, 7]
c = []
for s in set(a):
i = a.index(s)
count = a.count(s)
pom = []
for j in range(i, i + count):
if not pom:
pom.append(b[j])
elif abs(pom[-1] - b[j]) < 3:
pom.append(b[j])
if j + 1 == count:
pom.insert(0, s)
c.append(pom)
pom = []
else:
pom.insert(0, s)
c.append(pom)
pom = [b[j]]
print(c)
https://stackoverflow.com/questions/55117968
复制相似问题