python坐标系不均匀_如何在python中优雅地交织两个长度不均匀的列表?

I want to merge two lists in python, with the lists being of different lengths, so that the elements of the shorter list are as equally spaced within the final list as possible. i.e. I want to take [1, 2, 3, 4] and ['a','b'] and merge them to get a list similar to [1, 'a', 2, 3, 'b', 4]. It needs to be able to function with lists that aren't exact multiples too, so it could take [1, 2, 3, 4, 5] and ['a', 'b', 'c'] and produce [1, 'a', 2, 'b', 3, 'c', 4, 5] or similar. It needs to preserve the ordering of both lists.

I can see how to do this by a long-winded brute force method but since Python seems to have a vast array of excellent tools to do all sorts of clever things which I don't know about (yet) I wondered whether there's anything more elegant I can use?

NB: I'm using Python 3.3.

解决方案

if a is the longer list and b is the shorter

from itertools import groupby

len_ab = len(a) + len(b)

groups = groupby(((a[len(a)*i//len_ab], b[len(b)*i//len_ab]) for i in range(len_ab)),

key=lambda x:x[0])

[j[i] for k,g in groups for i,j in enumerate(g)]

eg

>>> a = range(8)

>>> b = list("abc")

>>> len_ab = len(a) + len(b)

>>> groups = groupby(((a[len(a)*i//len_ab], b[len(b)*i//len_ab]) for i in range(len_ab)), key=lambda x:x[0])

>>> [j[i] for k,g in groups for i,j in enumerate(g)]

[0, 'a', 1, 2, 'b', 3, 4, 5, 'c', 6, 7]

You can use this trick to make sure a is longer than b

b, a = sorted((a, b), key=len)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值