简体   繁体   中英

Iteratively collect first two elements of each vector of a matrix

I have a matrix:

matrix = [['F', 'B', 'F', 'A', 'C', 'F'],
          ['D', 'E', 'B', 'E', 'B', 'E'],
          ['F', 'A', 'D', 'B', 'F', 'B'],
          ['B', 'E', 'F', 'B', 'D', 'D']]

I want to remove and collect the first two elements of each sub-list, and add them to a new list.

so far i have got:

while messagecypher:
    for vector in messagecypher:
        final.extend(vector[:2])

the problem is; the slice doesn't seem to remove the elements, and I end up with a huge list of repeated chars. I could use .pop(0) twice, but that isn't very clean.

NOTE: the reason i remove the elements is becuase i need to keep going over each vector until the matrix is empty

You can keep your slice and do:

final = []
for i in range(len(matrix)):
    matrix[i], final = matrix[i][:2], final + matrix[i][2:]

Note that this simultaneously assigns the sliced list back to matrix and adds the sliced-off part to final .

Well you can use a list comprehension to get the thing done, but its perhaps counter-intuitive:

>>> matrix = [['F', 'B', 'F', 'A', 'C', 'F'],
          ['D', 'E', 'B', 'E', 'B', 'E'],
          ['F', 'A', 'D', 'B', 'F', 'B'],
          ['B', 'E', 'F', 'B', 'D', 'D']]
>>> while [] not in matrix: print([i for var in matrix for i in [var.pop(0), var.pop(0)]])
['F', 'B', 'D', 'E', 'F', 'A', 'B', 'E']
['F', 'A', 'B', 'E', 'D', 'B', 'F', 'B']
['C', 'F', 'B', 'E', 'F', 'B', 'D', 'D']

EDIT:

Using range makes the syntax look cleaner:

>>> matrix = [['C', 'B', 'B', 'D', 'F', 'B'], ['D', 'B', 'B', 'A', 'B', 'A'], ['B', 'D', 'E', 'F', 'C', 'B'], ['B', 'A', 'C', 'B', 'E', 'F']] 
>>> while [] not in matrix: print([var.pop(0) for var in matrix for i in range(2)])
['C', 'B', 'D', 'B', 'B', 'D', 'B', 'A']
['B', 'D', 'B', 'A', 'E', 'F', 'C', 'B']
['F', 'B', 'B', 'A', 'C', 'B', 'E', 'F']

Deleting elements is not an efficient way to go about your task. It requires Python to perform a lot of unnecessary work shifting things around to fill the holes left by the deleted elements. Instead, just shift your slice over by two places each time through the loop:

final = []
for i in xrange(0, len(messagecypher[0]), 2):
    for vector in messagecypher:
        final.extend(vector[i:i+2])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM