如何将元组或int的元组转换为在python中设置

时间:2017-04-18 00:13:29

标签: python-2.7 set tuples

我有以下类型的输入

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

2 个答案:

答案 0 :(得分:1)

你可以用条件修复那个flatten但是条件必须导致一个iterable,所以在这里我们使用一个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)可以使这更加通用。

答案 1 :(得分:0)

您的问题有点矫枉过正但它可能有助于未来的用户将嵌套的tuples展平为单tuplelist:< / p>

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]