如何从Python中的嵌套列表中提取特定元素?

huangapple go评论75阅读模式
英文:

How to extract specific elements from a nested list in Python?

问题

我有一个Python中的嵌套列表,其中每个元素也是一个列表。我想根据某些条件从这个嵌套列表中提取特定的元素。例如,假设我有以下嵌套列表:

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

我想提取每个内部列表中索引为1的所有元素,结果应为[2, 5, 8]。

在Python中,有什么有效的方法可以实现这一点?是否有任何内置的函数或方法可以帮助简化这个过程?非常感谢任何见解或代码示例。谢谢!

根据我的尝试,我期望提取的元素列表应包含每个内部列表中索引为1的元素,即[2, 5, 8]。然而,我没有得到期望的输出。

请问是否有人能指出我可能做错了什么,或者建议一个成功从嵌套列表中提取特定元素的替代方法?非常感谢您提前的帮助!

英文:

I have a nested list in Python, where each element is also a list. I would like to extract specific elements from this nested list based on certain conditions. For example, let's say I have the following nested list:

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I want to extract all the elements at index 1 from each inner list, resulting in the output [2, 5, 8].

What would be an efficient way to achieve this in Python? Are there any built-in functions or methods that can help simplify this process? Any insights or code examples would be greatly appreciated. Thank you!

Based on my attempt, I expected the extracted_elements list to contain the elements at index 1 from each inner list, which would be [2, 5, 8]. However, I'm not getting the desired output.

Could someone please point out what I might be doing wrong or suggest an alternative approach to successfully extract the specific elements from the nested list? Thank you in advance for your help!

答案1

得分: 1

你可以使用一个 列表推导式 轻松完成这个任务:

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = [sublist[1] for sublist in my_list]
英文:

You can do this easily enough with a list comprehension

my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = [sublist[1] for sublist in my_list]

答案2

得分: 1

你可以使用NumPy数组 https://numpy.org/doc/stable/user/basics.indexing.html

import numpy as np
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
np_array = np.array(my_list)

np_array[:, 1]  # 返回第二列
array([2, 5, 8])
英文:

You can use numpy array https://numpy.org/doc/stable/user/basics.indexing.html

>>> import numpy as np
>>> my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> np_array = np.array(my_list)

>>>  np_array[:,1] # returns the second column
array([2, 5,8])`

huangapple
  • 本文由 发表于 2023年6月13日 03:52:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76459878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定