Wolverine39
Wolverine39

Reputation: 83

Create a list with certain number of rows and columns in Python

I have a problem I can't seem to get right.

I have 2 numbers, A & B. I need to make a list of A rows with B columns, and have them print out 'R0CO', 'R0C1', etc.

Code:

import sys

A= int(sys.argv[1])

B= int(sys.argv[2])

newlist = []
row = A
col = B
for x in range (0, row): 
  newlist.append(['R0C' + str(x)])

  for y in range(0, col):
    newlist[x].append('R1C' + str(y))

print(newlist)

This is not working. The following is the output I get and the expected output: Program Output

Program Failed for Input: 2 3 Expected Output:

[['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']]

Your Program Output:

[['R0C0', 'R1C0', 'R1C1', 'R1C2'], ['R0C1', 'R1C0', 'R1C1', 'R1C2']]

Your output was incorrect. Try again

Upvotes: 3

Views: 17947

Answers (3)

Greg Mueller
Greg Mueller

Reputation: 526

Try changing your range commands as shown:

for x in range (row): 
  for y in range(col):

In fact, you have a second issue that you are not modifying the text properly:

newlist = []
row = A
col = B
for x in range (row):   
    sublist = []
    for y in range(col):
        sublist.append('R{}C{}'.format(x, y))
    newlist.append(sublist)

Upvotes: 0

Sefe
Sefe

Reputation: 14007

You are first adding R0Cx and then R1Cxy. You need to add RxCy. So try:

newlist = []
row = A
col = B
for x in range (0, row): 
  newlist.append([])

  for y in range(0, col):
    newlist[x].append('R' + str(x) + 'C' + str(y))

print(newlist)

Upvotes: 5

Elis Byberi
Elis Byberi

Reputation: 1452

You have to fill columns in a row while still in that row:

rows = []
row = 2
col = 3

for x in range(0, row):
    columns = []
    for y in range(0, col):
        columns.append('R' + str(x) + 'C' + str(y))

    rows.append(columns)


print(rows)

will print:

[['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']]

Upvotes: 0

Related Questions