创建子列表 [英] Creating sublists

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

问题描述

列表变平的相反.

给出一个长度为n的列表,返回一个长度为n的子列表的列表.

Given a list and a length n return a list of sub lists of length n.

def sublist(lst, n):
    sub=[] ; result=[]
    for i in lst:
        sub+=[i]
        if len(sub)==n: result+=[sub] ; sub=[]
    if sub: result+=[sub]
    return result

一个例子:

如果列表为:

[1,2,3,4,5,6,7,8]

n是:

3

返回:

[[1, 2, 3], [4, 5, 6], [7, 8]]

还有一种更雄辩/简洁的方法吗?

Is there a more eloquent / concise way?

顺便说一句,将列表追加到列表时(在上面的上下文中)是首选:

An aside, what is preferred when appending lists to lists (in the context above):

list1+=[list2]

或者:

list1.append(list2)

鉴于(根据Summerfeild的"Python 3编程"),它们是相同的吗?

Given that (according to Summerfeild's 'Programming in Python 3') they are the same?

谢谢.

推荐答案

可以使用还有石斑鱼成语:

In [19]: import itertools
In [20]: list(itertools.izip_longest(*[iter(seq)]*3))
Out[20]: [(1, 2, 3), (4, 5, 6), (7, 8, None)]

,但请注意,缺少的元素将填充为值None.如果 izip_longest 也可以采用fillvalue参数是理想的.

but note that missing elements are filled with the value None. izip_longest can take a fillvalue parameter as well if something other than None is desired.

list1+=[list2] –这次注意方括号–等效于list1.append(list2).编写代码时,我最优先考虑的是可读性, 没有速度.因此,我会选择list1.append(list2).但是,可读性是主观的,并且可能会受到您所熟悉的习惯用法的很大影响.

list1+=[list2] -- noting the brackets this time -- is equivalent to list1.append(list2). My highest priority when writing code is readability, not speed. For this reason, I would go with list1.append(list2). Readability is subjective, however, and probably is influenced greatly by what idioms you're familiar with.

幸运的是,在这种情况下,可读性和速度似乎是一致的:

Happily, in this case, readability and speed seem to coincide:

In [41]: %timeit list1=[1,2,3]; list1.append(list2)
1000000 loops, best of 3: 612 ns per loop

In [42]: %timeit list1=[1,2,3]; list1+=[list2]
1000000 loops, best of 3: 847 ns per loop

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

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