如何对列表列表的第 n 列进行切片?
我想对列表列表的第 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是你的意思吗?
Is this what you meant?
您可以使用
zip
转置矩阵:输出:
('b', 'a', 'h')
You could use
zip
to transpose your matrix:Output:
('b', 'a', 'h')