列表理解创建嵌套列表 [英] list comprehension creating nested lists

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

问题描述

我想创建嵌套的列表,每个月的天列表,每年的列表:

I'd like to create nested lists of days per month list per year list:

[[ 31, 29, 31, 30 ], [ 31, 28, 31, 30 ] ]

使用

mm = [ 1, 2, 3, 4 ]
yy = [ 2012, 2013 ]

但是我的代码:

[ [ result.append( calendar.monthrange( y, m )[ 1 ] ) for m in mm] for y in yy ]        

产生:

[31, 29, 31, 30,  31, 28, 31, 30 ]

有人可以告诉我我做错了什么吗?谢谢.BSL

Can someone please tell me what I've done wrong? Thanks. BSL

推荐答案

所以,我假设完整的代码如下所示:

So, I'm assuming the full code looks something like this:

result = []
[ [ result.append( calendar.monthrange( y, m )[ 1 ] ) for m in mm] for y in yy ]   
print(result)

代码的问题是您对列表理解的理解.列表理解会创建一个列表,因此您不应在其中添加任何内容到另一个列表.现在,您只需要将结果附加到结果上,然后打印结果,然后实际上就可以从列表理解中创建一个列表.

The problem with your code is your understanding of list comprehension. List comprehension creates a list, so you shouldn't be appending anything to another list within that. Right now, you are only appending things to result and then printing result and now actually creating a list from the list comprehension.

这里等同于您当前正在做的事情:

Here is the equivalent of what you are doing right now:

result  = [ ]
for y in yy:
    for m in mm:
        result.append( calendar.monthrange( y, m )[ 1 ] )

这里等同于您想要做的事情:

Here is the equivalent of what you want to be doing:

result  = [ ]
for y in yy:
    year = []
    for m in mm:
        year.append( calendar.monthrange( y, m )[ 1 ] )
    result.append(year)

这是列表理解版本:

>>> result = [[calendar.monthrange( y, m )[ 1 ] for m in mm] for y in yy]
>>> print(result)

[[31, 29, 31, 30], [31, 28, 31, 30]]

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

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