Reputation: 3382
Assuming I have a list of words:
l = ['example', 'to', 'a', 'list', 'of', 'words']
And I get an index i, let's say 10
.
What I need is to return the element in l
that contains the i-th char,
So in the example of 10, as the 10-th element (zero-based) is the l
from the word list
- what I need to return is the word list
.
Iv'e been trying to think of a simple way to do this, and I didn't find something elegant.
Any help will be appreciated!
Upvotes: 1
Views: 132
Reputation: 5531
Repeating each word for each of its letters, and then just picking the i-th word:
[s for s in l for _ in s][i]
Or more efficiently with a generator and itertools.islice
:
next(islice((s for s in l for _ in s), i, None))
Upvotes: 0
Reputation: 302
I got that wrong ... the @ -----Keeo it simple ...
In [1]: l = ['example', 'to', 'a', 'list', 'of', 'words']
In [2]: s = "".join(l)
In [3]: s
Out[3]: 'exampletoalistofwords'
In [4]: s[10]
Out[4]: 'l'
I believe, even in 1 line of code it is still readable (pythonic)
"".join( ['example', 'to', 'a', 'list', 'of', 'words'])[10]
Upvotes: -1
Reputation: 27515
You can use next and the walrus operator to keep track of your counts too. Basically keep subtracting the length of every string from i
and then once i is less than 0, that's the string:
l = ['example', 'to', 'a', 'list', 'of', 'words']
i = 10
result = next(s for s in l if (i:= i-len(s)) < 0)
Result:
'list'
Upvotes: 3
Reputation: 195553
from itertools import count
l = ['example', 'to', 'a', 'list', 'of', 'words']
c = count()
print(next(s for s in l for _, i in zip(s, c) if i == 10))
Prints:
list
Another solution (using bisect
module):
from bisect import bisect
from itertools import accumulate
l = ['example', 'to', 'a', 'list', 'of', 'words']
lengths = [*accumulate(map(len, l))]
print(l[bisect(lengths, 10)])
Upvotes: 1
Reputation: 569
i = 10
for word in l:
i -= len(word)
if i < 0:
break
# the value of word is 'list'
and if you want it in a function
def at_index(l, i):
for word in l:
i -= len(word)
if i < 0:
return word
return None
Upvotes: 3
Reputation: 24940
Something like this?
ind = 10
ll = 0
for item in l:
ll+=len(item)
if ll>=ind+1:
print(item)
break
Upvotes: 0