我有一个列表列表,看起来像
listOfLists = [
['a','b','c','d'],
['a','b'],
['a','c'],
['c','c','c','c']
]
Run Code Online (Sandbox Code Playgroud)
我想计算具有特定元素的列表的数量.例如,我的输出应该是
{'a':3,'b':2,'c':3,'d':1}
Run Code Online (Sandbox Code Playgroud)
如您所见,我不需要元素的总数.在这种情况下"c",尽管其总计数为5,但输出为3,因为它仅出现在3个列表中.
我正在使用计数器来获取计数.同样可以在下面看到.
line_count_tags = []
for lists in lists_of_lists:
s = set()
for element in lists:
s.add(t)
lines_count_tags.append(list(s))
count = Counter([count for counts in lines_count_tags for count in counts])
Run Code Online (Sandbox Code Playgroud)
所以,当我打印计数时,我明白了
{'a':3,'c':3,'b':2,'d':1}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更好的方法来实现我的目标.
我有以下程序扫描二维矩阵并检查行和列中0的位置,并使整个行和列(行和列中的0存在),矩阵中的0.
public static int[][] makeMatZero(int[][] matrix){
Boolean[] row = new Boolean[matrix.length];
Boolean[] col = new Boolean[matrix[0].length];
for(int i = 0;i< matrix.length;i++){
for(int j = 0;j< matrix[0].length;j++){
if(mat[i][j]==0){
row[i]=true;
col[j]=true;
}
}
}
for(int i = 0;i<row.length;i++){
if(row[i]){
removeRow(i,mat);
}
}
for(int i = 0;i<col.length;i++){
if(col[i]){
removeCol(i,mat);
}
}
return matrix;
}
public static void removeRow(int row, int[][] mat){
for(int j = 0;j<mat[0].length;j++){
mat[row][j]=0;
}
}
public static void removeCol(int col, int[][] mat){
for(int j = 0;j<mat.length;j++){
mat[j][col]=0;
}
}
Run Code Online (Sandbox Code Playgroud)
我在行if(row …