【问题标题】:How to convert a tuple of tuple or int to set in python如何将元组或int的元组转换为在python中设置
【发布时间】:2017-04-18 00:13:28
【问题描述】:

我有以下类型的输入

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

【问题讨论】:

    标签: python-2.7 set tuples


    【解决方案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) 来更通用。

    【讨论】:

    • 这对我有用! :D 非常感谢! +1 为 isinstance(tupl, tuple)
    【解决方案2】:

    这对于您的问题来说有点矫枉过正,但它可能会帮助未来的用户将嵌套的 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]
    

    【讨论】:

      猜你喜欢
      • 2019-05-15
      • 1970-01-01
      • 2021-09-12
      • 2016-02-15
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      相关资源
      最近更新 更多