Home > Enterprise >  How can I iterate a list of data using 2D list in python?
How can I iterate a list of data using 2D list in python?

Time:11-20

I want to create a variable called containing a 2D (nested) list of 2 rows and 3 columns literal containing the values like this:

3    14   67 
13   24   19

the code I have now is sth like this but the outcome doesn't give me the outcome I want:

for row in range(2):
    new_list = []
    for col in range(3):
        new_list.append(a_list)
print(new_list)

CodePudding user response:

You can use my code:

a_list = [3, 14, 67, 13, 24, 19] 
new_list = []
new_list  = [a_list[0:3]]
new_list  = [a_list[3:6]]

CodePudding user response:

Your problem is two-fold, you need to instantiate the correct number of lists to hold your elements; and you also need to pull elements from a_list in order.

You need to accumulate the elements of a_list into "rows" and you separately need to accumulate those rows into your outer list so that you end up with the structure:

[[3, 14, 67], [13, 24, 19]]

First, initialize an outer_list outside the loops. Then on each iteration of the outer loop, initialize an empty row list. Append the items from a_list to row in the inner loop. Then append row to the outer list at the end of the inner loop:

a_list = [3, 14, 67, 13, 24, 19]

num_rows = 2
num_cols = 3

# Make sure that num_rows * num_cols is equal to the length of the original list!

outer_list = []
for i in range(num_rows):
    row = []
    for j in range(num_cols):
        # row.append() <- grab the appropriate element from a_list
    outer_list.append(row)

I've left the hard part up to you, which is to figure out how to get an index using i and j that can access each element in a_list in order.

An easier approach would be to turn a_list into an iterator and repeatedly call next() on it, which negates the need for any tricky indexing. However, you should attempt to figure out how to index into a_list first before moving on so that you can get a decent understanding of how to work with lists.

  • Related