Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 index between values
#1
I have a list of words and I want to get the values of all words in between the word "and" but have to account for the number of words in between "and" varies as well as the amount of ands will vary in the list

list = ['visit', 'houston', 'and', 'san', 'antonio', 'and', 'austin', 'and', 'corpus', 'christi']

needing
list[1] # for Houston
list[3:4] #for joining san antonio
list[6] #for austin
list[8:] #for joining corpus christi

here is what i have so far

index_ands = [index for index, value in enumerate(list) if value == "and"] #gives the index of ands [2,5,7]
andleng = len(index_ands) #gives the number of ands is 3
    for ands in index_ands:
        #What goes here?
Quote
#2
Here is a way, using module itertools
>>> import itertools as itt
>>> L = ['visit', 'houston', 'and', 'san', 'antonio', 'and', 'austin', 'and', 'corpus', 'christi']
>>> [list(g) for k, g in itt.groupby(L, key=lambda word: word=='and') if not k]
[['visit', 'houston'], ['san', 'antonio'], ['austin'], ['corpus', 'christi']]
Avoid using 'list' as a variable name, it is the name of a built-in function.
scidam, snippsat, buran like this post
Quote
#3
Yes thanks Gribouillis that worked
Quote
#4
itertools.groupby is superior solution, but to answer OP-s original question ('What goes here?')

>>> lst = ['visit', 'houston', 'and', 'san', 'antonio', 'and', 'austin', 'and', 'corpus', 'christi']
>>> indexes = [i for i, v in enumerate(lst) if v == 'and'] 
>>> result = []
>>> start = 1
>>> for i in indexes:
...     result.append(lst[start:i])
...     start = i + 1
... else:
...     result.append(lst[start:])
...
>>> print(result)
[['houston'], ['san', 'antonio'], ['austin'], ['corpus', 'christi']]
Gribouillis likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Get all values of for loop with an index BollerwagenIng 2 308 Aug-09-2019, 07:58 AM
Last Post: BollerwagenIng

Forum Jump:


Users browsing this thread: 1 Guest(s)