Is there a more Pythonic way of changing No to `[]` than

Is there a more pythonic way to do this ?:

            if self.name2info[name]['prereqs'] is None:
                self.name2info[name]['prereqs'] = []
            if self.name2info[name]['optionals'] is None:
                self.name2info[name]['optionals'] = []

The reason I do this is because I need to repeat these steps later. They are Nonefor starters, because this is the default value. I was unable to make []a default value.

Thank.

+3
source share
5 answers

If you prefer this:

self.name2info[name]['prereqs'] = self.name2info[name]['prereqs'] or []

+4
source

If you cannot fix the input, you can do it (it gets β€œbetter” if you need to add more):

for prop in ['prereqs', 'optionals']:
    if self.name2info[name][prop] is None:
        self.name2info[name][prop] = []

, , (, , - - ). , , None -ness :

prereqs = self.name2info[name]['prereqs']
if prereqs is not None:
    for prereq in prereqs:
        do_stuff(prereq)

, - , , () :

try:
    my_iterable_obj = iter(my_obj)
except TypeError:
    # not iterable
+1

:

if not self.name2info[name]['prereqs']: self.name2info[name]['prereqs'] = []

self.name2info[name]['prereqs'] = [] if not self.name2info[name]['prereqs'] else self.name2info[name]['prereqs']
0

dict . Pythonic self.name2info [name] , , dict:

rec = self.name2info[name]
for key in "prereqs optionals required elective distance".split():
    if key not in rec or rec[key] is None:
        rec[key] = []

, , "AP_credit", .

0

If you repeat them, I assume that they are saved in the list. In this case, it would probably be better to combine some of the above approaches.

seq=list(map(lambda x: x or [], seq))

This is a short way to do it. As far as I know, transformations in map () are faster than explicit for loops, since loops are executed in the base C code.

0
source

Source: https://habr.com/ru/post/1753594/


All Articles