我有一个程序,该程序使用python docx从表的单元格中的列表中打印随机值。表,单元格和行的数量取决于用户输入。我需要先比较表的单元格,然后再在另一个表的相同数字单元格中输入值。
例如。
number_of_tables = 5 #input by user
number_of_rows = 4 #input by user
number_of_cols = 7 #input by user
list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
docu = Document()
for tablenum in range(number_of_tables):
tablename = docu.add_table(rows = number_of_rows, cols = number_of_cols)
for rowiteration in tablename.rows[0:]:
for cells in rowiteration.cells:
cells.text = random.choices(list)
如果表1中的单元格(0,0)具有'a',我不想在表2中的单元格(0,0)中以'a'打印,甚至更多。
[基本上,您想从list
中选择一个随机值,但排除一个(或多个)值-另请参见this question。
因此,您应该构造另一个列表,但不包含要排除的值-例如,从选择中排除值'a'
的示例:
random.choice([s for s in list if s != 'a'])
对于您的情况,您将必须像这样在其他表中排除同一单元格(r,c)
中的所有值:
for tablenum in range(number_of_tables):
tablename = docu.add_table(rows=number_of_rows, cols=number_of_cols)
for r, rowiteration in enumerate(tablename.rows):
for c, cells in enumerate(rowiteration.cells):
exclude = [docu.tables[num].cell(r,c).text for num in range(tablenum)]
cells.text = random.choice([s for s in list if s not in exclude])