我有几个对象:一些字符串和一些元组。对于每个不是字符串的项目,我想将它变成一个对象元组。例如:从字符串创建一个元组元素python
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
括号只是用于描述一个元组时,逗号可能意味着别的东西:
不要使用名字'list';您现在正在屏蔽内置类型。 – 2014-12-13 00:18:11