Python 相当于 C# 的 .Select?
我有一个 Python 对象列表,它们每个都有一个 id 属性。我想获得这些 ID 的列表。
在 C# 中,我会写
myObjects.Select(obj => obj.id);
How would I do this in Python?
I've got an list of objects in Python, and they each have an id
property. I want to get a list of those IDs.
In C# I'd write
myObjects.Select(obj => obj.id);
How would I do this in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在这里查看“列表理解”部分:http://docs.python.org/tutorial/ datastructs.html
如果您的起始列表名为
original_list
并且新列表名为id_list
,您可以执行以下操作:Check out the section on "List Comprehension" here: http://docs.python.org/tutorial/datastructures.html
If your starting list is called
original_list
and your new list is calledid_list
, you could do something like this:如果列表很大并且您只需要处理一次 id,那么还有生成器表达式。
生成器表达式不支持随机访问,但会根据需要获取每个 id,因此可以避免一次构建列表。生成器表达式是
xrange
,就像列表推导式是range
一样。关于生成器表达式的另一个警告是,只有当其中的任何资源仍然打开时才可以访问它。例如,以下代码将失败。
在这种情况下,等效的列表理解将起作用。
If it's a big list and you only need to process the ids once then there are also generator expressions.
A generator expression doesn't support random access but will get you each id on demand and so avoids building a list all at once. generator expressions are to
xrange
as list comprehensions are torange
.One more caveat with generator expressions is that it can only be accessed for as long as any resource within it is still open. For example, the following code will fail.
The equivalent list comprehension would work in this case.
如果您想要在 Python 中直接等效于 C# select,但需要使用第三方库,则可以使用 asq< /a> 包,它通过 Python 可迭代提供受 LINQ-for-objects 启发的实现。使用 asq,您的问题中的 C# 代码将变为:
或者,与 asq 的另一个功能相结合:
If you want a direct equivalent of C# select in Python, at the cost of using a third-party library, you could use the asq package which provides a LINQ-for-objects inspired implementation over Python iterables. Using asq the C# code in your question would become:
or, combined with another feature of asq:
头脑正常的人不会按照以下方式执行此操作,但这里是为了以防万一它在更复杂的示例中派上用场
Nobody in their right mind would do this the following way, but here it is in case it comes in handy in a more complex example