Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of C#'s .Select?

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?

like image 280
mpen Avatar asked Nov 23 '10 22:11

mpen


People also ask

What is C in Python?

The C function always has two arguments, conventionally named self and args. The self argument points to the module object for module-level functions; for a method it would point to the object instance. The args argument will be a pointer to a Python tuple object containing the arguments.

Is Python as fast as C?

Python is an excellent tool enabling just that. It allows for focusing on the idea itself and not be bothered with boilerplate code and other tedious things. However, Python comes with a major drawback: It is much slower than compiled languages like C or C++.

Why is C faster than Python?

C/C++ is relatively fast as compared to Python because when you run the Python script, its interpreter will interpret the script line by line and generate output but in C, the compiler will first compile it and generate an output which is optimized with respect to the hardware.

Can you use C in Python?

Conclusion. The python default implementation is written in C programming and it's called CPython. So it's not very uncommon to use C functions in a python program.


2 Answers

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 called id_list, you could do something like this:

id_list = [x.id for x in original_list]
like image 167
Brent Writes Code Avatar answered Sep 23 '22 01:09

Brent Writes Code


[obj.id for obj in myObjects]
like image 29
Ignacio Vazquez-Abrams Avatar answered Sep 25 '22 01:09

Ignacio Vazquez-Abrams