循环遍历列表中的每个元素

时间:2014-09-10 04:04:12

标签: python list

如何循环遍历python中列表中的每个元素。 例如,如果我有列表:

list = ["abc",3,(10,(11,12))]

我希望将列表拆分为:['a','b','c',3,10,11,12]

现在我有:

def combinelist(list):
   l = []
   for item in list:
      l.append(item)
    return l

然而,这只返回完全相同的列表。我如何深入了解列表中的每个元素并拆分每个元素?谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

好吧,我不知道优雅的编码方式,所以......

l = ["abc",3,('x','y')]

o = []
for i in l:
    if isinstance(i, str):
        o.extend(list(i))
    elif isinstance(i, (tuple, list)):
        o.extend(i)
    else:
        o.append(i)

print o

或者:

o = []
for i in l:
    try:
        o.extend(list(i)) # can it be casted to sequence?
    except TypeError:
        o.append(i)
print o

甚至:

o = []
for i in l:
    if isinstance(i, (str, list, tuple)):
        o.extend(list(i)) 
    else:
        o.append(i)
print o
相关问题