Handle either a list or single integer as an argument

后端 未结 6 881
萌比男神i
萌比男神i 2020-12-05 01:59

A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and ha

6条回答
  •  忘掉有多难
    2020-12-05 02:44

    I'd go along with Sharkey's version, but use a bit more duck typing:

    def select_rows(to_select):
        try:
            len(to_select)
        except TypeError:
            to_select = [to_select]
    
        for row in range(0, table.numRows()):
            if _table.item(row, 1).text() in to_select:
                table.selectRow(row)
    

    This has the benefit of working with any object that supports the in operator. Also, the previous version, if given a tuple or some other sequence, would just wrap it in a list. The downside is that there is some performance penalty for using exception handling.

提交回复
热议问题