Вопрос

Just say I have an integer in Python, ex: 100.

I'd like to convert this integer into a list counting up to this integer, ex: [1,2,3,... 100]

What is the most efficient way to do this?

(In case you're wondering why I want to do this, it's because the Django Paginate library I want to use needs a list -- if there's a more elegant way to use Paginate without doing this, please let me know).

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

Решение

The Python range() built-in does exactly what you want. E.g:

range(1, 101)

Note that range() counts from 0, as is normal in Computer Science, so we need to pass 1, and it counts until the given value, not including - hence 101 here to count to 100. So generically, you want range(1, n+1) to count from 1 to n.

Also note that in 3.x, this produces an iterator, not a list, so if you need a list, then you can simply wrap list() around your call to range(). That said - most of the time it's possible to use an iterator rather than a list (which has large advantages, as iterators can be computed lazily), in that case, there is no need to make a list (in 2.x, functionality like that of range in 3.x can be achieved with xrange().

Другие советы

The solution given by Lattyware is correct for generating the list, but if your using Django pagination you can just use paginator_instance.page_range

https://docs.djangoproject.com/en/dev/topics/pagination/#django.core.paginator.Paginator.page_range

You can use range or xrange. xrange is faster, but returns an iterator.

>>>range(1,101)
[1, 2, 3, ... , 99, 100]

>>> xrange(1,101)
xrange(1, 101)

>>>list(xrange(1,101))
[1, 2, 3, ... , 99, 100]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top