python - 列表的字符串或元组的字符串

标签 python string iterable

我有一个类属性,它可以是一个字符串或一个字符串列表。我想将它转换成一个元组,这样列表可以正常转换,但单个字符串变成单项元组:

[str, str] --> (str, str)

str --> (str, )

不幸的是 tuple('sting') 返回 ('s', 't', 'r', 'i', 'n', 'g')这不是我所期望的。是否可以不进行类型检查?

最佳答案

类型检查将是实现这一目标的好方法。否则您将如何决定输入是列表还是字符串?

您可以创建一个函数来测试输入是列表还是字符串并适本地返回并按您认为合适的方式处理其余部分。类似的东西

>>> def convert_to_tuple(elem):
        if isinstance(elem, list):
            return tuple(elem)
        elif isinstance(elem, basestring):
            return (elem,)
        else:
            # Do Something
            pass


>>> convert_to_tuple('abc')
('abc',)
>>> convert_to_tuple(['abc', 'def'])
('abc', 'def')

你也只能检查字符串,(假设是 Python 2.x,将 Py3 中的 basestring 替换为 str)

>>> def convert_to_tuple(elem):
        if isinstance(elem, basestring):
            return (elem,)
        else:
            return tuple(elem)


>>> convert_to_tuple('abc')
('abc',)
>>> convert_to_tuple(('abc', 'def'))
('abc', 'def')
>>> convert_to_tuple(['abc', 'def'])
('abc', 'def')

也可以将函数转换为单行代码。

>>> def convert_to_tuple(elem):
        return (elem,) if isinstance(elem, basestring) else tuple(elem)

关于python - 列表的字符串或元组的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18556448/

相关文章:

c# - Windows 应用程序 C# 字符串组合框

python - 具有可迭代工作的 Python for 循环如何工作?

python - 将 pandas Dataframe 的行转换为可迭代的字符串列表

python - 高维结构化 numpy 数据类型上的 numba 类型错误

python - 带有 Python 的 JSON "object must be str, not dict"

python - 将新闻写入 CSV 文件(Python 3,BeautifulSoup)

c++ - 为什么 stoi/atoi 向我提供编译器错误?

javascript - 按 utf-8 字节位置提取子字符串

python - 如何找到第n次出现在列表中的项目的索引?

Python - 使用 pyqtgraph 快速绘图(16ms)?