list - 三重嵌套列表综合python。可能吗?
问题描述
我正在练习嵌套列表理解,我遇到了一些我无法解决的问题,也无法在网上找到任何解决方案:<
nested_lista = [[2,1,2,3],[1,2,3,4],[4,4,[16,1,3]]]
使用循环很容易遍历这个嵌套列表的每一层
def nested_loops():
for x in nested_lista:
for y in x:
print(y)
if type(y) == list:
for z in y:
print(z)
输出:
2
1
2
3
1
2
3
4
4
4
[16, 1, 3]
16
1
3
现在我试图通过嵌套列表理解来实现类似的输出,但无论我尝试什么,它都不起作用;/
这是我想出的:
[[[print(y) for y in z if type(z)==list]print(z) for z in x]for x in nested_lista]
或者至少我尝试遍历最后一层,但它也不起作用
[[[print(y) for y in z if type(z)==list] for z in x]for x in nested_lista]
有可能解决这个问题还是我应该放弃?
解决方案
2 周假期后头脑清醒,我花了 +-30 分钟才得到答案。
准备好更多的巢穴:
answer = [[[print(y) if type(y) is not list else print(x) for x in y] if type(y) == list else print(y) for y in z]for z in nested_lista]
较短的结果相同:
answer2 = [[[print(x) for x in y] if type(y) == list else print(y) for y in z]for z in nested_lista]
输出:
2
1
2
3
1
2
3
4
4
4
16
1
3
不知道为什么我得到了“ - ”。
推荐阅读
- node.js - 找到在NodeJS中找到对象列表的欧几里得距离的最佳方法
- javascript - 方法每 10 秒触发一次并在 app.component.html 文件中重复运行
- vba - 组合框来选择具有多个重复项的值并以每个重复记录的值逐行填充表单中的文本框?
- flutter - 在 initState Flutter 中初始化下拉菜单的正确方法
- reactjs - 使用来自 prop-types 的 InferProps<> 时,键入 props 会传播
- python - 使用 python 从 XML 中获取只需要的元素时出现错误“list.remove(x): x not in list”
- firebase - Firebase Cloud Function Set Timeout 540s 但以 60s 结束
- javascript - 如何将键/值对添加到 lodash _pick 方法?
- php - 提交由 GoDaddy 托管在 Plesk 上的 HTML 和 PHP 联系表单时出错
- c - 无法从指针读取值