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)
这篇关于将列表或单个整数作为参数处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将列表或单个整数作为参数处理
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01