list comprehension creating nested lists

限于喜欢 提交于 2021-01-28 04:37:06

问题


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

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

with

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

but my code:

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

produces:

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

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


回答1:


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)

And here is the list comprehension version of that:

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

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


来源:https://stackoverflow.com/questions/36037922/list-comprehension-creating-nested-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!