3

I'm trying to add an extra column to a 2D array in Python but I'm stuck. I have a 2D array like below:

['000', '101']
['001', '010']
['010', '000']
['011', '100']

Then I swap 2 elements from the 2nd column and have something like this:

['000', '101']
['001', '000']
['010', '010']
['011', '100']

I want to take the last column right now and add it as the 3rd one like this:

['000', '101', '101']
['001', '010', '000']
['010', '000', '010']
['011', '100', '100']

But I only managed to get this:

['000', '101']
['001', '000']
['010', '010']
['011', '100']
101
000
010
100

I'm adding a column like this:

col = column(data,1)
data_res += col

I'm creating an array like this:

with open('data.txt', 'r') as f:
     for line in f:
         line_el = line.split()
         data.append(line_el)

I'm swapping like this:

def swap(matrix, id_l, id_r):
    matrix[id_l][1], matrix[id_r][1] = matrix[id_r][1],matrix[id_l][1]
    return matrix

Any ideas?

1
  • 1
    Are they numpy arrays or lists? Your data is not valid python syntax. Commented Jan 16, 2017 at 21:41

2 Answers 2

5

Since you are writing your 2D list as a list of lists (Row Major Order), adding a column means adding an entry to each row.

It seems you already have some data created like this:

# Create a 2D list
data = [['000', '101'],['001', '010'],['010', '000'],['011', '100']]

So now you could add a new column identical to the last column like this:

# Loop through all the rows
for row in data:
  lastColumn = row[-1]
  # Now add the new column to the current row
  row.append(lastColumn)
Sign up to request clarification or add additional context in comments.

Comments

0

A list comprehension can do this quickly. This code doesn't perform the swap, but it looks like you have that working already. :)

data = [['000', '101'],['001', '010'],['010', '000'],['011', '100']]
print [x + [x[1]] for x in data]

# [
#     ['000', '101', '101'],
#     ['001', '010', '010'],
#     ['010', '000', '000'],
#     ['011', '100', '100']
# ]

with open('data.txt', 'r') as f:
    for line in f:
        line_el = line.split()
        data.append([x + [x[1]] for x in line_el])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.