Python:计算二维列表列中元素的出现次数

对于两组,您可以position相应地传递和调整宽度:


fig, ax = plt.subplots()


stacked_data.plot(kind="bar", stacked=True, width=0.4, 

                  ax=ax, position=0)

stacked_data2.plot(kind="bar", stacked=True, width=0.4, 

                   ax=ax, position=1, hatch='//')


ax.set_xlim(right=len(stacked_data)-0.5)

输出:


慕哥9229398
浏览 246回答 3
3回答

慕容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]]

守候你守候我

numpy 很方便res=[col.tolist().count('X') for col in numpy.transpose(data)]res[0]='nums'data+[res]或者,res=numpy.count_nonzero(numpy.array (data)=='X',axis=0).tolist()res[0]='nums'data+[res]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python