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

时间:2009-06-15 23:23:36

标签: python list function integer

函数应根据行名称选择表中的行(本例中为第2列)。它应该能够将单个名称或名称列表作为参数并正确处理它们。

这就是我现在所拥有的,但理想情况下不会出现这种重复的代码,并且可以智能地使用类似异常的方法来选择处理输入参数的正确方法:

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 个答案:

答案 0 :(得分:21)

实际上我同意Andrew Hare's answer,只需传递一个包含单个元素的列表。

但如果你真的必须接受一个非名单,那么在这种情况下如何将其变成一个列表?

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)

答案 1 :(得分:17)

您可以重新定义函数以获取任意数量的参数,例如:

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)

答案 2 :(得分:11)

我会这样做:

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)

并期望参数始终是一个列表 - 即使它只是一个元素的列表。

记住:

  

要求宽恕比获得许可更容易。

答案 3 :(得分:3)

我赞同Sharkey的版本,但是使用更多的鸭子打字:

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)

这样可以使用任何支持in运算符的对象。此外,如果给出一个元组或其他序列,之前的版本只会将其包装在一个列表中。缺点是使用异常处理会有一些性能损失。

答案 4 :(得分:0)

一个简单的包装器就可以处理列表或单个对象的情况

  def wrap_list(val):
    if type(val) is list:
      return val
    return [val] 

答案 5 :(得分:0)

使用numpy不太通用,但比较简洁:

numpy.unique()

通过仅保留类似数组或标量的唯一值来自动处理,并返回唯一值或标量的列表。

import numpy as np

def select_rows(to_select):
   to_select = np.unique(to_select)

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