Вопрос

index = [x for x in range(0,81)]
membership_columns = {
    'column_0': index[0:81:9]
    'column_1': index[1:81:9]
    'column_2': index[2:81:9]
    'column_3': index[3:81:9]
    'column_4': index[4:81:9]
    'column_5': index[5:81:9]
    'column_6': index[6:81:9]
    'column_7': index[7:81:9]
    'column_8': index[8:81:9]
    }

Is it possible to squeeze this into a dictionary comprehension? Also, is the list comprehension on line 1 necessary? I wasnt sure how I turn each key into a list comprehension by itself.

Это было полезно?

Решение

Absolutely it's possible. I would suggest doing this like so:

{('column_%d' % i): index[i:81:9] for i in xrange(9)}

Also the first list comprehension is not quite needed as just doing:

index = range(0,81)

would accomplish the same thing.

You could also replace all of the list slicing with xranges, which are only going to generate your needed values. You could do that like so:

{('column_%d' % i): range(i,81, 9) for i in xrange(9)}

since the range function in python takes a step parameter. See the docs.

That said, despite this looking more elegant, you do take a performance hit over slicing that will probably get worse with larger comprehensions. At this size it's not really noticeable:

import timeit
>>> timeit.timeit("{('column_%d' % i): range(i,81, 9) for i in xrange(9)}", number = 100000)
1.3790168762207031
>>> timeit.timeit("index=range(0,81);{('column_%d' % i): index[i:81:9] for i in xrange(9)}", number = 100000)
1.1949927806854248

Apparently the string formatting here is slower than I thought. As pointed out by martineau you can get a considerable speed increase using concatenation instead:

>>> timeit.timeit("{('column_' + str(i)): range(i,81,9) for i in xrange(9)}", number = 100000)
0.914525032043457

However with larger values of i it starts to become considerable:

>>> timeit.timeit("{('column_%d' % i): range(i,81, 9) for i in xrange(90)}", number = 100000)
12.220430135726929
>>> timeit.timeit("index=range(0,81);{('column_%d' % i): index[i:81:9] for i in xrange(90)}", number = 100000)
9.669343948364258
>>> timeit.timeit("index=range(0,81);{('column_' + str(i)): index[i:81:9] for i in xrange(90)}", number = 100000)
7.163957118988037
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top