代码之家  ›  专栏  ›  技术社区  ›  Boosted_d16

排序表python时排除给定列

  •  0
  • Boosted_d16  · 技术社区  · 12 年前

    我正在尝试对表进行排序,但希望在排序时按名称排除给定的列。换句话说,给定的列应该保持在排序之前的位置。这旨在处理“不知道”、“NA”等栏目。

    我使用的API是独特的,并且是特定于公司的,但它使用python。

    此API中的表是一个对象,它是一个行列表,其中每一行是一个单元格列表,每个单元格是一个单元值列表。

    我目前有一个对表排序的工作函数,但我想编辑/修改它,以按名称排除给定的列,但我很难找到方法。

    仅供参考——“矩阵”可以被认为是表格本身。

    def SortColumns(byRow=0, usingCellValue=0, descending=True):
    """
    :param byRow: Use the values in this row to determine the sort order of the 
            columns.
    :param usingCellValue: When there are multiple values within a cell use this
            to control which value row within each cell is used for sorting
            (zero-based)
    :param descending: Determines the order in which the values should be
            sorted. 
    """
    
       for A in range(0,Matrix.Count):
            for B in range(0,Matrix.Count):
                if(A==B):
                    continue; #do not compare rows against eachother
    
                valA = Matrix[byRow][A][usingCellValue].NumericValue if Matrix[byRow][A].Count > usingCellValue else None;
                valB = Matrix[byRow][B][usingCellValue].NumericValue if Matrix[byRow][B].Count > usingCellValue else None;
    
                if(descending):
                    if valB < valA:
                        Matrix.SwitchColumns(A,B)
                else:
                    if valA < valB:
                        Matrix.SwitchColumns(A,B)
    

    我正在考虑添加一个新的参数,它接受一个列名称列表,并使用此参数绕过这些列。

    类似于:

    def SortColumns(fixedcolumns, byRow=0,usingCellValue=0,descending=True):
    
    1 回复  |  直到 9 年前
        1
  •  0
  •   Kevin    12 年前

    在遍历列时,可以使用 continue 语句跳过不想移动的列。在两个循环的开始处设置以下条件:

    for A in range(0,Matrix.Count):
        a_name = ??? #somehow get the name of column A
        if a_name in fixedcolumns: continue
        for B in range(0,Matrix.Count):
            b_name = ??? #somehow get the name of column B
            if b_name in fixedcolumns: continue
            if(A==B):
                continue