2017-04-18 205 views
0

设置,我有以下类型的输入如何转换元组的元组或INT在python

tuple_of_tuple_or_int = ((3,8),4) # it may be like (4,(3,8)) also 

我想将其转换为一组像

{3,8,4} # in any order 

我已经试过这:

[element for tupl in tuple_of_tuple_or_int for element in tupl] 

但它引发以下错误:

TypeError: 'int' object is not iterable 

回答

1

您可以修复与条件拉平但条件必须产生一个可迭代所以在此我们使用了一个1元组:

[element for tupl in tuple_of_tuple_or_int 
     for element in (tupl if isinstance(tupl, tuple) else (tupl,))] 

这导致输入((3,8),4)要处理,就好像它是((3,8),(4,))

Python 2.7.3 
>>> tuple_of_tuple_or_int = ((3,8),4) 
>>> [element for tupl in tuple_of_tuple_or_int 
...   for element in (tupl if isinstance(tupl, tuple) else (tupl,))] 
[3, 8, 4] 

这可以通过替换isinstance(tupl, tuple)而变得更一般。

+0

这对我的作品! :D非常感谢! isinstance为+1(tupl,元组) –

0

这是一个有点矫枉过正您的问题,但它可能有助于未来的用户平嵌套tuples成一个单一的tuplelist

def flatten(T): 
    if not isinstance(T,tuple): return (T,) 
    elif len(T) == 0: return() 
    else: return flatten(T[0]) + flatten(T[1:]) 

tuple_of_tuple_or_int = ((3,8),4) 

print flatten(tuple_of_tuple_or_int) # flatten tuple 
# (3, 8, 4) 

print list(flatten(tuple_of_tuple_or_int)) # flatten list 
# [3, 8, 4]