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?
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.
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++.
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.
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.
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]
[obj.id for obj in myObjects]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With