def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
iterable = (((2,4),6,(9,(3,7))))
_list = []
def addToList(elem, listRef):
"""
elem: item you want to insert into the list
listRef: list you want to append stuff to
"""
try:
for x in elem:
addToList(x, listRef) # recursive call
except:
listRef.append(elem) # add the item if it's not iterable
# Main
for item in iterable:
addToList(item, _list) # iterate tuple, pass ea. element into addToList, pass the list you want to append to
print _list
tup = (((2,4),6,(9,(3,7))))
listversion = []
def loopthroughtup(tup):
for i in tup:
if type(i) == tuple:
print str(i) + " is a tuple"
loopthroughtup(i)
else:
print str(i) + " is not a tuple"
listversion.append(i)
loopthroughtup(tup)
print listversion
您需要展平元组中的元组,请参见Flattening a shallow list in Python和James Brady提供的解决方案:
一个非常基本的答案,但是应该按照你的要求去做。使用
try
和except
查看项是否可iterable。如果为True,则递归函数;如果为False,则将项添加到列表中。你知道吗Python的经验法则,快速失败和廉价失败:)
警告:如果元组中有字符串,则每个字符都将附加到
_list
(因为字符串是iterable)。我没有围绕字符串进行设计,因为您没有指定是否使用它们。你知道吗这是一个递归的好例子——尽管尼古拉斯已经有了类似的答案。你知道吗
在这里,我们为您提供的元组设置了一个。我们还设置了一个空列表,您需要在其中输入元组。你知道吗
函数从元组开始,循环遍历每个元素。如果元素是一个元组,它会再次递归调用函数,直到找到一个非元组。然后将其插入列表中。你知道吗
相关问题 更多 >
编程相关推荐