I have a for loop to create a list, can I use list comprehension?

Let there be a list of values ​​and an arbitrary integer.

values = ['5', '3', '.', '.', '7', '.', '.', '.', '.', '6', '.', '.', '1', '9', '5', '.', '.', '.', '.', '9', '8', '.', '.', '.', '.', '6', '.', '8', '.', '.', '.', '6', '.', '.', '.', '3', '4', '.', '.', '8', '.', '3', '.', '.', '1', '7', '.', '.', '.', '2', '.', '.', '.', '6', '.', '6', '.', '.', '.', '.', '2', '8', '.', '.', '.', '.', '4', '1', '9', '.', '.', '5', '.', '.', '.', '.', '8', '.', '.', '7', '9']

n = 9

I would like to group values ​​with nnumbers in a string.

Suppose that n=9, that is, 9 numbers will be in a row.

The result should be like this:

grouped_values = [
     ['5', '3', '.', '.', '7', '.', '.', '.', '.'],
     ['6', '.', '.', '1', '9', '5', '.', '.', '.'],
     ['.', '9', '8', '.', '.', '.', '.', '6', '.'],
     ['8', '.', '.', '.', '6', '.', '.', '.', '3'],
     ['4', '.', '.', '8', '.', '3', '.', '.', '1'],
     ['7', '.', '.', '.', '2', '.', '.', '.', '6'],
     ['.', '6', '.', '.', '.', '.', '2', '8', '.'],
     ['.', '.', '.', '4', '1', '9', '.', '.', '5'],
     ['.', '.', '.', '.', '8', '.', '.', '7', '9']]

I can do it like this:

def group(values, n):
   rows_number = int(len(values)/n) # Simplified. Exceptions will be caught.
   grouped_values = []

   for i in range(0, rows_number):
      grouped_values.append(values[i:i+9])

But there is a suspicion that you can use list comprehension here. Could you help me understand how this can be done?

+4
source share
1 answer

Just move the expression in the call list.append()to the front and add a loop for:

grouped_values = [values[i:i + 9] for i in range(rows_number)]

, . ; values[0:9], values[1:10] .. , 9, 8 , . 9, range(0, len(values), n) , rows_number:

grouped_values = [values[i:i + n] for i in range(0, len(values), n)]

, :

<list_name> = []

for <targets> in <iterable>:
    <list_name>.append(<expression>)

<expression> <list_name>,

<list_name> = [<expression> for <targets> in <iterable>]

, list_name , . , .

, <expression> , .

, , <expression> ; Python.

for if , for if ; ,

<list_name> = []

for <targets1> in <iterable1>:
    if <test_expression>:
        for <targets2> in <iterable2>:        
            <list_name>.append(<expression>)

<list_name> = [
    <expression>
    for <targets> in <iterable>
    if <test_expression>
    for <targets2> in <iterable2>
]
+11

Source: https://habr.com/ru/post/1692834/


All Articles