I'm barely learning python and trying to write some code, but running in some issues trying to access the next element in the list.
Here is part of my code:
for word2 in vocab_list:
index2 = 0
for elem in sentence2:
if (elem == word2 and nextElem == nextWord2)
do something
index2 += 1
The issue is in the nextElem
and nextWord2
, how do I access them given that I'm in the current iteration?
You can use zip
for this, this will also prevent you from the IndexError
's:
for word2, nextWord2 in zip(vocab_list, vocab_list[1:]):
for elem, nextElem in zip(sentence2, sentence2[1:]):
if (elem == word2 and nextElem == nextWord2)
#Do something
Demo:
>>> lis = range(5)
>>> for item, next_item in zip(lis, lis[1:]):
... print item, next_item
...
0 1
1 2
2 3
3 4
Note that zip
returns a list, so if the input data to zip
is huge then it's better to use itertools.izip
, as it returns an iterator. And instead of slicing get iterators using itertools.tee
.
In the demo you can see that in the loop zip
stops at item=3
, that's because zip
short-circuits to the shortest iterable. If you want the output to be 4, some_default_value
, then use itertools.izip_longest
, it allows you provide default values for missing items in the shorter iterables.
You can access any member of the list if you iterate by index number of the array vice the actual element:
for i in range(len(vocab_list)-1):
for j in range(len(sentence)-1):
if(vocab_list[i]==sentence[j] and vocab_list[i+1]==sentence[j+1]):
print "match"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With