处理列表或单个整数作为参数

52 投票
6 回答
46199 浏览
提问于 2025-04-15 12:16

这个函数的作用是根据表格中的行名(在这里是第二列)来选择行。它应该能够接受一个名字或者一组名字作为输入,并且能够正确处理这些输入。

我现在的代码是这样的,但理想情况下,我希望能减少重复的代码,并且能聪明地使用一些像异常处理这样的方式来选择合适的方法来处理输入参数:

def select_rows(to_select):
    # For a list
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)
    # For a single integer
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() == to_select:
            table.selectRow(row)

6 个回答

12

我会这样做:

def select_rows(to_select):
    # For a list
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)

并且我会期待这个参数总是一个列表——即使它只是一个包含一个元素的列表。

记住:

请求原谅比请求许可要简单。

29

你可以重新定义你的函数,让它可以接收任意数量的参数,像这样:

def select_rows(*arguments):
    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in arguments:
            table.selectRow(row)

这样你就可以像这样传递一个参数:

select_rows('abc')

也可以像这样传递多个参数:

select_rows('abc', 'def')

如果你已经有一个列表的话:

items = ['abc', 'def']
select_rows(*items)
33

其实我同意 Andrew Hare的回答,只需要传一个包含单个元素的列表就可以了。

不过如果你真的需要接受一个不是列表的东西,那就可以在这种情况下把它转换成列表嘛。

def select_rows(to_select):
    if type(to_select) is not list: to_select = [ to_select ]

    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)

在一个只有一个元素的列表上使用'in'操作,性能损失应该不会太大:-) 但这也提醒你,如果你的'to_select'列表可能很长,可以考虑把它转换成集合,这样查找会更高效。

def select_rows(to_select):
    if type(to_select) is list: to_select = set( to_select )
    elif type(to_select) is not set: to_select = set( [to_select] )

    for row in range(0, table.numRows()):
        if _table.item(row, 1).text() in to_select:
            table.selectRow(row)

撰写回答