开发者

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

开发者 https://www.devze.com 2023-01-05 21:43 出处:网络
Is there a more Pythonic way of doing this?: if self.name2info[name][\'prereqs\'] is None: self.name2info[name][\'prereqs\'] = []

Is there a more Pythonic way of doing 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 iterate over those later. They're None to begin with sometimes because that's the default value. It's my workaround to开发者_Go百科 not making [] a default value.

Thanks.


If you prefer this:

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


If you can't fix the input you could do this (becomes 'better' if you need to add more):

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

But replacing these values to be iterating over the empty list you just added doesn't make a whole lot of sense (unless maybe if you're appending something to this list at some point). So maybe you could just move the test for None-ness right before the iteration:

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

Slightly going off-topic now, but if you ever want to test if an item is iterable at all, a common (pythonic) way would be to write:

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


You could do it this way:

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

or this way

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


Every one of those attribute and dict lookups takes time and processing. It's Pythonic to look up self.name2info[name] just once, and then work with a temporary name bound to that 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] = []

Now if need to add another category, like "AP_credit", you just add that to the string of key names.


If you're iterating over them I assume they're stored in a list. In which case combining some of the above approaches would probably be best.

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

Is a concise way of doing it. To my knowledge conversions in map() are faster than explicit for loops because the loops are run in the underlying C code.

0

精彩评论

暂无评论...
验证码 换一张
取 消