有条件地合并列表 [英] Conditionally merge lists

查看:75
本文介绍了有条件地合并列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个列表

[16, 0, 0, ';', 17, 0, 2, ';', 0, 2, 1, ';']
  [-1, 0, ';', 0, -2, ';', -2, -1, ';']

有没有一种简单的方法可以在满足';'条件下合并这些列表元素个性,而不是分别遍历它们并组合在一起?

Is there a simpler way to merge these list elements conditionally on meeting the ';' character than individually iterating through them both and combining them?

输出应为

[16, 0, 0, -1, 0, ';', 17, 0, 2, 0, -2, ';', 0, 2, 1, -2, -2,';']

推荐答案

def get_part(lst,sep=';'):
    out = []
    for i in lst:
        if i == sep:
           yield out
           out = []
        else:
           out.append(i)

现在我们可以将您的列表压缩在一起:

Now we can zip together your lists:

merged = []
for l1,l2 in zip(get_part(list1),get_part(list2)):
    merged.extend(l1)
    merged.extend(l2)
    merged.append(';')

当然,从本质上讲,这本质上是对它们两者进行迭代并组合在一起.因此,为了回答您的问题,我认为没有更好的方法.

Of course, at it's core, this is essentially iterating over both of them and combining ... so in answer to your question, I don't think there's a better way.

也许存储列表的更好方法是将它们存储为列表列表-例如:

Perhaps a better way to store your lists would be storing them as a list of lists -- e.g.:

list1 = [[16, 0, 0], [ 17, 0, 2], [ 0, 2, 1] ]

这样存储,您可以执行以下操作:

stored like this, you can just do:

merged = [ l1 + l2 for l1,l2 in zip(list1,list2) ]

这篇关于有条件地合并列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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