Handle either a list or single integer as an argument(将列表或单个整数作为参数处理)
问题描述
函数应根据行名(在本例中为第 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)
这篇关于将列表或单个整数作为参数处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将列表或单个整数作为参数处理
基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01