将列表或单个整数作为参数处理
问题描述
函数应根据行名(在本例中为第 2 列)选择表中的行.它应该能够将单个名称或名称列表作为参数并正确处理它们.
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)
解决方案
其实我同意Andrew Hare的回答,只是传递一个包含单个元素的列表.
Actually I agree with Andrew Hare's answer, 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)
在单个项目列表上执行in"的性能损失不太可能很高 :-)但这确实指出了如果您的to_select"列表可能很长,您可能需要考虑做的另一件事:考虑将其转换为一个集合,以便查找更有效.
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)
相关文章