从python字符串创建一项元组

从python字符串创建一项元组,python,list,tuples,Python,List,Tuples,我有两个对象:一些字符串和一些元组。对于每一个不是字符串的项,我希望将其转换为一个单对象元组。例如: s = 'spam' #turns into: t = ('spam') 然后,我想将这些元组中的每一个都附加到一个列表中。代码: mylist = [] items = ('spam', 'eggs', ('shrubbery', 1, 'toast'), ('foo', 'bar')) #If not already a tuple, each item is converted into

我有两个对象:一些字符串和一些元组。对于每一个不是字符串的项,我希望将其转换为一个单对象元组。例如:

s = 'spam' #turns into:
t = ('spam')
然后,我想将这些元组中的每一个都附加到一个列表中。代码:

mylist = []
items = ('spam', 'eggs', ('shrubbery', 1, 'toast'), ('foo', 'bar'))
#If not already a tuple, each item is converted into a tuple, then appended to `mylist`
#In the end, `list` should be:
mylist = [('spam'), ('eggs'), ('shrubbery', 1, 'toast'), ('foo', 'bar')]
我已经试过:

for i in items:
    if type(i) != tuple:
        i = tuple(i)
    mylist.append(i)
这会将每个独立字符串转换为其字符的元组,这不是我想要的


如何执行此操作?

一项元组由逗号定义,而不是括号:

>>> 1,
(1,)
>>> (1)
1
当逗号可能表示其他内容时,括号仅用于描绘元组

请参见表达式文档中的:

带括号的表达式列表产生表达式列表产生的结果:如果列表至少包含一个逗号,则产生一个元组;否则,它将生成组成表达式列表的单个表达式

因此,请使用:

if not isinstance(i, tuple):
    i = i,

注意使用
isinstance()
以及测试类型

您可以通过列表理解来完成此操作:

>>> items = ('spam', 'eggs', ('shrubbery', 1, 'toast'), ('foo', 'bar'))
>>>
>>> [item if isinstance(item, tuple) else (item,) for item in items]
[('spam',), ('eggs',), ('shrubbery', 1, 'toast'), ('foo', 'bar')]

不要使用名称
列表
;您现在正在屏蔽内置类型。