慕容3067478
这是一个可能的解决方案:result = data + [['nums'] + [sum(1 if data[row][col] == 'X' else 0 for row in range(1, len(data))) for col in range(1, len(data[0]))]]此操作后result如下所示:[["", "a", "b", "c"], ["a", "X", 1, "X"], ["b", "X", 2, "X"], ["c", "X", "foo", 3]] ["nums", 3, 0, 2]]
互换的青春
我修改了你的代码。X所以我添加了一个字典来记录一列中出现的次数。data[1:]--> 将忽略第一行 row[1:]--> 将忽略每一行的第一列值。def foo(data): new_data = data[1:] d = { i:0 for i in range(len(data))} d.update({0:"nums"}) for row in (new_data): for col_num, col in enumerate(row[1:], start=1): if col == "X": d[col_num] += 1 #e.g: if indexes = [1, 3, 1, 3, 1]: there is 3 "X":s in column 1, and 2 "X":s in column 3 data.append(list(d.values())) return datafoo(data)[['', 'a', 'b', 'c'], ['a', 'X', 1, 'X'], ['b', 'X', 2, 'X'], ['c', 'X', 'foo', 3], ['nums', 3, 0, 2]]