简体   繁体   English

具有嵌套列表的列表理解

[英]List comprehensions with nested lists

Would like to ask question related to nested lists in Python. 想问一下与Python中的嵌套列表有关的问题。

I have a nested list 我有一个嵌套清单

list_1 = [[1,3,0,1], [1,1,0,2,3,0,4,], [2,1,2,2,3,4]]

I want to perform rounding and dision operation on nested list but keep it grouped as it is now (to make it more clear I need to flatten list perform operations and that unflatten it again in same groups). 我想对嵌套列表执行舍入和提取操作,但现在将其分组(为了更清楚地显示,我需要展平列表执行操作,然后再次将其展平在同一组中)。

For example the result for list 'list_1' after division by 2 shoud be 例如,列表“ list_1”的结果除以2后应为

list_2 = [[0.5,1.5,0,0.5],[0.5,0.5,0,1,1.5,0,2],[1,0.5,1,1,1.5,2]]

The code I use to perform this for signle list is below: 我用于执行签名列表的代码如下:

list_2 = [round(b,2) for b in [a / 2 for a in list_1]]

Could you please suggest way to solve this issue. 您能否建议解决此问题的方法。 Currently I am getting error 目前我遇到错误

"unsupported operand type(s) for /: 'list' and 'float'"

Thank you. 谢谢。

Fixing your code - 修改您的代码-

[[j / 2. for j in i] for i in list_1] 

If you're worried about performance, you could multiply by .5 instead of dividing by 2 (you may not see significant differences considering this is a quadratic solution, but it should count for something ). 如果您担心性能,可以乘以.5而不是除以2(考虑到这是二次解法,您可能看不到明显的差异,但应该算作什么 )。

[[j * .5 for j in i] for i in list_1] 

The docs have a section just for Nested List Comprehensions , please consider having a read through. 该文档的一部分仅适用于嵌套列表推导 ,请考虑通读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM