处理一个列表或单个整数作为参数 [英] Handle either a list or single integer as an argument

查看:101
本文介绍了处理一个列表或单个整数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数应根据行名选择表中的行(在这种情况下为第2列)。它应该能够使用单个名称或名称列表作为参数并正确处理。



这是我现在拥有的,但理想情况下不会将这个重复的代码和类似异常的东西用于智能地选择正确的方式来处理输入参数:

pre $ def c select_rows( to_select):
#列表
用于范围内的行(0,table.numRows()):
如果_table.item(row,1).text()in to_select:
table.selectRow(row)
#对于单个整数
(0,table.numRows())中的行:
if _table.item(row,1)。 text()== to_select:
table.selectRow(row)


解决方案<实际上我同意上面的Andrew Hare,只是通过一个单一元素的列表。



但是如果你真的必须接受一个非列表,关于在这种情况下将它变成列表?

  def s elect_rows(to_select):
如果type(to_select)不是list:to_select = [to_select]

用于范围内的行(0,table.numRows()):
if _table.item(row,1).text()in to_select:
table.selectRow(row)

在单个项目列表中执行'in'的性能损失可能不高:-)
但是,这确实指出了另一件你可能想要考虑的事情,如果你的'to_select '列表可能很长:考虑将其转换为一个集合,以便查找更高效。

  def select_rows(to_select):$如果type(to_select)为list,则b $ b:to_select = set(to_select)
elif type(to_select)未设置:to_select = set([to_select])

(0,table.numRows()):
如果_table.item(row,1).text()在to_select:
table.selectRow(row)

----- N


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 handle them correctly.

This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument:

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)

解决方案

Actually I agree with Andrew Hare above, just pass a list with a single element.

But if you really must accept a non-list, how about just turning it into a list in that case?

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)

The performance penalty for doing 'in' on a single-item list isn't likely to be high :-) But that does point out one other thing you might want to consider doing if your 'to_select' list may be long: consider casting it to a set so that lookups are more efficient.

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)

-----N

这篇关于处理一个列表或单个整数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆