在 Python 中处理单值元组的最佳实践是什么? [英] What's the best practice for handling single-value tuples in Python?

查看:34
本文介绍了在 Python 中处理单值元组的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用第 3 方库函数,它从文件中读取一组关键字,并应该返回一组值.只要至少有两个关键字,它就可以正确执行此操作.但是,在只有一个关键字的情况下,它返回一个原始字符串,而不是大小为 1 的元组.这是特别有害的,因为当我尝试做类似

I am using a 3rd party library function which reads a set of keywords from a file, and is supposed to return a tuple of values. It does this correctly as long as there are at least two keywords. However, in the case where there is only one keyword, it returns a raw string, not a tuple of size one. This is particularly pernicious because when I try to do something like

for keyword in library.get_keywords():
    # Do something with keyword

,在单个关键字的情况下,for 连续迭代字符串的每个字符,在运行时或其他情况下都不会抛出异常,但对我来说完全没用.

, in the case of the single keyword, the for iterates over each character of the string in succession, which throws no exception, at run-time or otherwise, but is nevertheless completely useless to me.

我的问题有两个:

显然这是库中的一个错误,这是我无法控制的.我怎样才能最好地解决它?

Clearly this is a bug in the library, which is out of my control. How can I best work around it?

其次,一般来说,如果我正在编写一个返回元组的函数,那么确保正确生成具有一个元素的元组的最佳实践是什么?例如,如果我有

Secondly, in general, if I am writing a function that returns a tuple, what is the best practice for ensuring tuples with one element are correctly generated? For example, if I have

def tuple_maker(values):
    my_tuple = (values)
    return my_tuple

for val in tuple_maker("a string"):
    print "Value was", val

for val in tuple_maker(["str1", "str2", "str3"]):
    print "Value was", val

我明白

Value was a
Value was  
Value was s
Value was t
Value was r
Value was i
Value was n
Value was g
Value was str1
Value was str2
Value was str3

当只有一个元素时,修改函数 my_tuple 以实际返回元组的最佳方法是什么?我是否明确需要检查大小是否为 1,并使用 (value,) 语法单独创建元组?这意味着任何有可能返回单值元组的函数都必须这样做,这看起来很笨拙且重复.

What is the best way to modify the function my_tuple to actually return a tuple when there is only a single element? Do I explicitly need to check whether the size is 1, and create the tuple seperately, using the (value,) syntax? This implies that any function that has the possibility of returning a single-valued tuple must do this, which seems hacky and repetitive.

这个问题有什么优雅的通用解决方案吗?

Is there some elegant general solution to this problem?

推荐答案

您需要以某种方式测试类型,如果它是字符串或元组.我会这样做:

You need to somehow test for the type, if it's a string or a tuple. I'd do it like this:

keywords = library.get_keywords()
if not isinstance(keywords, tuple):
    keywords = (keywords,) # Note the comma
for keyword in keywords:
    do_your_thang(keyword)

这篇关于在 Python 中处理单值元组的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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