Exact wording from assignment: We pass in 2 numbers, A and B. You should create a list with A rows and B columns. You should then populate each cell like this … 'R0C0', 'R0C1', 'R0C2' etc. I was able to create the list with all 0's but not able to modify to correct output.
Was given this but don't know how to implement.
for row in rows: # Each row
for col in cols: # The columns on the current row
print('This is row: %s and col: %s' % (row,col)
A= int(sys.argv[1])
B= int(sys.argv[2])
# Your code goes here
a = [([0]*B) for row in range(0 , A)]
print(a)
Expected Output: [['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']] Your Program Output: [[0, 0, 0], [0, 0, 0]]
You're not using either A
nor B
in your result, you're using 0
, that's why you're getting [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
.
You can fix that by using string formatting to get the row and column you want.
num_rows = int(sys.argv[1])
num_columns = int(sys.argv[2])
result = [["R{row}C{col}".format(row=row, col=col) for col in range(num_columns)] for row in range(num_rows)]
Or, more succinctly (with f-strings in Py3.6+):
result = [[f"R{row}C{col}" for col in range(num_columns)] for row in range(num_rows)]
You could also initialize your list, then iterate through and set each value, but I'm not sure what you gain from doing this in this example.
import itertools
def make_2d_list(self, rows, columns):
"""Makes a 2D list with None for each value."""
return [[None for _ in range(columns)] for _ in range(rows)]
base_list = make_2d_list(num_rows, num_columns)
for row, col in itertools.product(range(num_rows), range(num_columns))
# itertools.product is a concise form of nested for loops.
# These two expressions are equivalent:
#
# for a, b, c, d, e in itertools.product(as, bs, cs, ds, es):
# ...
#
# for a in as:
# for b in bs:
# for c in cs:
# for d in ds:
# for e in es:
# ...
base_list[row][col] = f"R{row}C{col}"
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.