[英]How can I return a list of objects within a tuple in python?
我對python問題有些困惑。 我想編寫一個函數,該函數返回嵌套在元組中的所有對象的列表。
例如,我希望能夠將元組((((2,4),6,(9,(3,7))))變成[2,4,6,9,3,7]。我真的不確定如何開始,因為元組是不可變的。
您需要展平元組的元組,請參閱展平Python中的淺表和James Brady提供的解決方案:
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
這是遞歸的一個很好的例子-盡管尼古拉斯已經有了類似的答案。
在這里,我們建立了一個您介紹的元組。 我們還設置了一個空列表,您想在其中添加元組。
該函數從元組開始,並遍歷每個元素。 如果元素是一個元組,它將再次遞歸調用該函數,直到獲得非元組為止。 然后將其插入列表。
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
一個非常基本的答案,但是應該按照您的要求進行。 使用try
和except
來查看該項目是否可迭代。 如果為True,則遞歸該函數;如果為False,則將該項目添加到列表中。
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
Python的經驗法則,快速失敗並且廉價失敗:)
警告 :如果您在元組中包含字符串,則每個字符都將附加到_list
(因為字符串是可迭代的)。 我沒有圍繞字符串進行設計,因為您沒有指定是否使用它們。
from re import findall
a = ((143,243),534,((55,356)),645)
print findall('\d+', str(a))
# ['143', '243', '534', '55', '356', '645']
b = ((1,2),5,((5,6)),345)
print findall('\d+', str(b))
# ['1', '2', '5', '5', '6', '345']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.