如何将列表分为n个相等的部分,python [英] How to divide a list into n equal parts, python

查看:93
本文介绍了如何将列表分为n个相等的部分,python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出( any )单词列表lst,我应该将其分为10个相等的部分.

Given (any) list of words lst I should divide it into 10 equal parts.

x = len(lst)/10

如何给这些零件赋予变量名?

how to give these parts variable names?

在输出中,我需要10个变量(part1, part2... part10),其中的单词数为x.

In the output I need 10 variables (part1, part2... part10) with x number of words in it.

推荐答案

单行返回列表列表,并给出列表和块大小:

One-liner returning a list of lists, given a list and the chunk size:

>>> lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]

测试:

>>> x = range(20, 36)
>>> print x
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]

>>> lol(x, 4)
[[20, 21, 22, 23], 
 [24, 25, 26, 27], 
 [28, 29, 30, 31], 
 [32, 33, 34, 35]]

>>> lol(x, 7)
[[20, 21, 22, 23, 24, 25, 26], 
 [27, 28, 29, 30, 31, 32, 33], 
 [34, 35]]

更新:

我认为问题实际上是在问一个函数,给定一个列表和一个数字,该函数返回一个包含$(number)个列表的列表,原始列表中的各项均匀分布.因此,您的lol(x,7)示例应真正返回[[20,21,22],[23,24,25],[26,27],[28,29],[30,31],[32 ,33],[34,35]. –马克里安

I think the question is really asking is a function which, given a list and a number, returns a list containing $(number) lists, with the items of the original list evenly distributed. So your example of lol(x, 7) should really return [[20,21,22], [23,24,25], [26,27], [28,29], [30,31], [32,33], [34,35]]. – markrian

好吧,在这种情况下,您可以尝试:

Well, in this case, you can try:

def slice_list(input, size):
    input_size = len(input)
    slice_size = input_size / size
    remain = input_size % size
    result = []
    iterator = iter(input)
    for i in range(size):
        result.append([])
        for j in range(slice_size):
            result[i].append(iterator.next())
        if remain:
            result[i].append(iterator.next())
            remain -= 1
    return result

我确定这可以改善,但是我感到很懒. :-)

I'm sure this can be improved but I'm feeling lazy. :-)

>>> slice_list(x, 7)
[[20, 21, 22], [23, 24, 25], 
 [26, 27], [28, 29], 
 [30, 31], [32, 33], 
 [34, 35]]

这篇关于如何将列表分为n个相等的部分,python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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