Having a list or str, like this:
value = 'Water'
Indexing with i=4 value[4]
gives me 'r'.
How can i turn my indexing to use larger (unlimited range) values like 16
to get 'r', or 40
for 'W'?
You could use modulus:
>>> value = "Water"
>>> value[16 % len(value)]
'a'
>>> value[40 % len(value)]
'W'
I think you should use remainder operator:
>>> value = 'Water'
>>> value[16%len(value)]
'a'
>>> value[40%len(value)]
'W'
Here is an itertools
solution, but it's not pretty...
>>> import itertools
>>> value = 'Water'
>>> next(itertools.islice(itertools.cycle(value), 16))
'a'
>>> next(itertools.islice(itertools.cycle(value), 40))
'W'
itertools.cycle
will repeat your input iterable ( 'Water'
in this case) infinitely. itertools.islice
allows you to slice an iterable as if it were a list
. Calling next
once just returns the first value from the slice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.