嵌套列表中的列表理解

发布于 2024-09-27 04:59:45 字数 423 浏览 4 评论 0原文

我有一个类似 [["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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小…红帽 2024-10-04 04:59:45

这将为您提供所需的列表:

[lx for li in fieldlist for lx in li[1] if li[1]]

This will give you the list you want:

[lx for li in fieldlist for lx in li[1] if li[1]]
空袭的梦i 2024-10-04 04:59:45

Pythonic 解决方案类似于:

>>> from collections import Counter
>>> Counter(v for (field, values) in fieldlist
...           for v in values)
Counter({'a': 2, 'b': 2, 'c': 1, 'f': 1})

A Pythonic solution would be something like:

>>> from collections import Counter
>>> Counter(v for (field, values) in fieldlist
...           for v in values)
Counter({'a': 2, 'b': 2, 'c': 1, 'f': 1})
从来不烧饼 2024-10-04 04:59:45

列表理解:

>>> s = [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]
>>> [x for y, z in s for x in z]
['a', 'b', 'c', 'a', 'b', 'f']
>>>

if li[1] 的目的是什么?如果 li[1] 是空列表或其他容器,则测试是多余的。否则,您应该编辑您的问题以解释它可能是什么。

List comprehension:

>>> s = [["foo", ["a", "b", "c"]], ["bar", ["a", "b", "f"]]]
>>> [x for y, z in s for x in z]
['a', 'b', 'c', 'a', 'b', 'f']
>>>

What is the purpose of your if li[1]? If li[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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文