Roberto Guglielmo
Roberto Guglielmo

Reputation: 1

Accessing one row at a time in an array

Say I have a matrix of strings

array = [['hello', 'how', 'are', 'you'],
         ['I', 'am', 'doing', 'okay'],
         ['Okay', 'did','you', 'do', 'your', 'hw','?']]

And I want to search every other line for key words since there suppose to be two people in a conversation.

For example this, matrix has 3 rows and every odd line corresponds to person A and every even line corresponds to person B.

However, I just care about what person A writes, since I'm only searching for words person A said.

Upvotes: 0

Views: 63

Answers (3)

jpp
jpp

Reputation: 164773

The first issue to clear up is terminology. Technically, what you have is not an array or a matrix. You have a list of lists.

To iterate over every other line, you can use list indexing. For a list A, this takes the format A[start:stop:step], where start, stop and step are integers (positive or negative) and stop is not included in the range. If you omit an integer, it is assumed to be 0 for start, None for end, 0 for step.

Therefore, to iterate over the first person's words, you can use:

for words_a in array[::2]:
    # do something

Or, for the second person's words, use array[1::2].

Note the above method involves building new lists. A more memory-efficient method is to use an iterator, such as itertools.slice:

from itertools import islice

for words_a in islice(array, 0, None, 2):
    # do something

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54223

If you don't mind eschewing the often-idiomatic list comprehension, you could use a simple for loop with a manual next call afterwards. This has the advantage of having a smaller memory footprint, but is obviously more verbose.

acc = []

arrayiter = iter(array)

for line in arrayiter:
    acc.extend([word for word in line if word in keywords])
    next(arrayiter, None)  # skips the next line

Upvotes: 0

Hans Musgrave
Hans Musgrave

Reputation: 7141

Here's an example. Your question doesn't make it clear what you want to do with matching lines, but the idea is that you skip every other line with a slice [::2]. This does create a copy of your list, so working with indices directly like xrange(0, len(array), 2) may be more efficient (use range() in Python3).

keywords = ['did', 'you']

array = [['hello', 'how', 'are', 'you'],
         ['I', 'am', 'doing', 'okay'],
         ['Okay', 'did','you', 'do', 'your', 'hw','?']]

print [line for line in array[::2] if any(key in line for key in keywords)]

Upvotes: 2

Related Questions