[英]Populating cells within a 2d list in python
Exact wording from assignment: We pass in 2 numbers, A and B. You should create a list with A rows and B columns.作业中的确切措辞:我们传入 2 个数字 A 和 B。您应该创建一个包含 A 行 B 列的列表。 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.
然后,您应该像这样填充每个单元格……'R0C0'、'R0C1'、'R0C2' 等。我能够创建全 0 的列表,但无法修改为正确的输出。
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]]预期输出:[['R0C0', 'R0C1', 'R0C2'], ['R1C0', 'R1C1', 'R1C2']] 你的程序输出:[[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]]
.您在结果中既没有使用
A
也没有使用B
,而是使用0
,这就是为什么您得到[[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+):或者,更简洁(在 Py3.6+ 中使用 f 字符串):
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}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.