如何使用另一个列表中的匹配值索引来复制列表值? [英] How to duplicate list values using matching value index from another list?

查看:105
本文介绍了如何使用另一个列表中的匹配值索引来复制列表值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

A = [476, 1440, 3060, 3060, 500,500]
B = [0,4,10,15]

注意:列表B的长度将始终等于列表A中的单个值加上配对值的数量.更新后的列表B将与列表A的长度匹配.

NOTE: length of list B will always be equal to individual plus number of paired values in list A. Updated list B will match the length of the list A.

我想检查列表A中的重复值,并使用其索引位置来重复列表B中的对应值.例如,列表A的A [2] = A [3]和A [4] = A [5](3060和500),因此基于此我想复制B [2]和B [3]并将它们分别添加到B [3]和B [5].因此更新后的列表B看起来像:

I want to check for duplicate values in the list A and use its indexed position to duplicate corresponding value in the list B. For example, list A has A[2]=A[3] and A[4]=A[5] (3060 and 500), so based on this I want to duplicate B[2] and B[3] and add these at B[3] and B[5] respectively. So updated list B would look like:

B = [0,4,10,10,15,15] 

我尝试以下操作以获取重复值的开始索引:

I tried following to get start index of duplicate values:

C = [x==A[i-1] for i,x in enumerate(A)][1:]

for idx,l in enumerate(C):
    if l == True:
        print "idx"

但是很快就将这一更改纳入列表B.任何建议都将是有益的.

But running short to incorporate this change into list B. Any suggestions would be appreciative.

推荐答案

这是一个幼稚的实现(不确定我是否满足您的要求):

Here is a naive implementation (not sure if I got your requirement correct):

>>> from itertools import groupby
>>> A = [476, 1440, 3060, 3060, 500, 500]
>>> B = [0, 4, 10, 15]
>>> Result = []
>>> for i, g in enumerate(groupby(A)):
        Result += [B[i]] * len(list(g[1]))


>>> Result
[0, 4, 10, 10, 15, 15]

这篇关于如何使用另一个列表中的匹配值索引来复制列表值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆