在python中平均分配列表 [英] Equally distribute a list in python
本文介绍了在python中平均分配列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在python中有以下列表:
Suppose I have the following list in python:
a = ['a','b','c','d','e','f','g','h','i','j']
我如何分配这样的列表:
How do I distribute the list like this:
['a','f']
['b','g']
['c','h']
['d','i']
['e','j']
如果我有一个长度不等的列表并将多余的"项目放在一个单独的列表中,该如何实现?
And how do I achieve this if I have a list of unequal length and putting the 'superfluous' items into a separate list?
我希望能够以指示的方式将原始列表的元素分发到 n 个部分.
I want to be able to distribute the elements of the original list into n parts in the indicated manner.
因此,如果n = 3,那将是:
So if n=3 that would be:
['a','d','g']
['b','e','h']
['c','f','i']
和单独列表中的多余"元素
and the 'superfluous' element in a separate list
['j']
推荐答案
您可以使用> c0> 并具有列表理解功能:
You can use zip
with a list comprehension:
def distribute(seq):
n = len(seq)//2 #Will work in both Python 2 and 3
return [list(x) for x in zip(seq[:n], seq[n:])]
print distribute(['a','b','c','d','e','f','g','h','i','j'])
#[['a', 'f'], ['b', 'g'], ['c', 'h'], ['d', 'i'], ['e', 'j']]
这篇关于在python中平均分配列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文