如何对列表列表的第 n 列进行切片?

发布于 2025-01-11 16:28:48 字数 472 浏览 0 评论 0原文

我想对列表列表的第 n 列进行切片。 例如,

matrix = [
    ["c","b","a","c"],
    ["d","a","f","d"],
    ["g","h","i","a"]
]

我需要转置列表然后使用索引吗?例如

transposed = []
for i in range(len(matrix)+1):
   transposed.append([row[i] for row in matrix])
transposed[1]
>>> ['b','a','h']

,或者有没有办法直接在嵌套列表上使用索引?

我正在尝试类似的事情:

matrix[:][1]
>>>['d','a','f','d']

但这不起作用,正如我发现的那样。

谢谢

I want to slice the the nth column of a list of lists.
e.g.

matrix = [
    ["c","b","a","c"],
    ["d","a","f","d"],
    ["g","h","i","a"]
]

Do i need to transpose the list and then use indices? e.g.

transposed = []
for i in range(len(matrix)+1):
   transposed.append([row[i] for row in matrix])
transposed[1]
>>> ['b','a','h']

or is there a way to use indices directly on the nested list?

I was trying something like:

matrix[:][1]
>>>['d','a','f','d']

but this does not work as I found out.

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

埋葬我深情 2025-01-18 16:28:48
>>> [column[1] for column in matrix]
['b', 'a', 'h']

这是你的意思吗?

>>> [column[1] for column in matrix]
['b', 'a', 'h']

Is this what you meant?

爱人如己 2025-01-18 16:28:48

您可以使用 zip 转置矩阵:

list(zip(*matrix))[1]

输出:('b', 'a', 'h')

You could use zip to transpose your matrix:

list(zip(*matrix))[1]

Output: ('b', 'a', 'h')

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