嵌套列表中的列表理解
我有一个类似 [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]< 的列表/code>
我想将其拆分出来,这样我就可以计算出 As、B 等的总数。但我对 Python 很陌生,并且对此有些了解。
我正在使用 [lx for lx in [li[1] for li in fieldlist if li[1]]]
尝试获取包含子子列表中所有项目的列表,但是返回包含第一个子列表的列表 ([["a", "b", "c"], ["a", "b", "f"]]
而不是包含我很确定我只是想错了,因为我是列表推导式和 Python 的新手,
有人有一个好的方法来做到这一点(是的,我知道我选择的名称) (lx,li)太可怕了)
谢谢。
I have a list like [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]
and I'm wanting to split it out so I can get a count of the total number of As, Bs, etc. but I'm new to Python and having a bit of a time of it.
I'm using [lx for lx in [li[1] for li in fieldlist if li[1]]]
to try and get a list with all of the items in the sub-sublists, but that returns a list with the first sublists ([["a", "b", "c"], ["a", "b", "f"]]
instead of a list with the contents of those sublists. I'm pretty sure I'm just thinking about this wrong, since I'm new to list comprehensions and Python.
Anyone have a good way to do this? (and yes, I know the names I chose (lx, li) are horrible)
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这将为您提供所需的列表:
This will give you the list you want:
Pythonic 解决方案类似于:
A Pythonic solution would be something like:
列表理解:
if li[1]
的目的是什么?如果 li[1] 是空列表或其他容器,则测试是多余的。否则,您应该编辑您的问题以解释它可能是什么。List comprehension:
What is the purpose of your
if li[1]
? Ifli[1]
is an empty list or other container, the test is redundant. Otherwise you should edit your question to explain what else it could be.