Last active
July 5, 2017 14:16
-
-
Save JokerMartini/728eb6370bbf344fe180 to your computer and use it in GitHub Desktop.
Python: Collect attribute from a list of objects where attribute exists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
existing_names = [getattr(x, "name", "") for x in nodes if type(x).__name__ == node_class] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
values = [ getattr(x.data, "age", "") for x in nodes ] | |
>> ['5', '7', '12'] | |
# However if the attribute 'age' is not there it returns this | |
>> ['5', '', '7', '', '12'] | |
values = [ getattr(x.data, 'age', '') for x in nodes ] | |
values = filter(bool, values) | |
>> ['5', '7', '12'] | |
# or use these options | |
values = [ getattr(x.data, 'age') for x in nodes if hasattr(x.data, 'age')] | |
values = [ x.data.age for x in nodes if hasattr(x.data, 'age')] | |
values = [ x.data.age for x in nodes if hasattr(x, 'data') and hasattr(x.data, 'age') ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment