【问题标题】:Merge two tuples into one将两个元组合并为一个
【发布时间】:2013-05-03 21:50:34
【问题描述】:

我有两个元组

("string1","string2","string3","string4","string5","string6","string7")

("another string1","another string2",3,None,"another string5",6,7)

我想做这样的事情:

("string1another string1","string2another string2","string33","string4","string5another string5","string66","string77").

这样的结果也可以:

("string1another string1","string2another string2","string33","string4None","string5another string5","string66","string77")

但由于我是 Python 新手,我不确定如何操作。组合这两个元组的最佳方法是什么?

【问题讨论】:

    标签: python python-3.x merge tuples


    【解决方案1】:

    使用zip 和生成器表达式:

    >>> t1=("string1","string2","string3","string4","string5","string6","string7")
    >>> t2=("another string1","another string2",3,None,"another string5",6,7)
    

    第一个预期输出:

    >>> tuple("{0}{1}".format(x if x is not None else "" ,
                                 y if y is not None else "") for x,y in zip(t1,t2))
    ('string1another string1', 'string2another string2', 'string33', 'string4', 'string5another string5', 'string66', 'string77')
    

    第二个预期输出:

    >>> tuple("{0}{1}".format(x,y) for x,y in zip(t1,t2)) #tuple comverts LC to tuple
    ('string1another string1', 'string2another string2', 'string33', 'string4None', 'string5another string5', 'string66', 'string77')
    

    使用此ternary expression 处理None 值:

    >>> x = "foo"
    >>> x if x is not None else ""
    'foo'
    >>> x = None
    >>> x if x is not None else ""
    ''
    

    【讨论】:

    • +1,但是……为什么将 listcomp 传递给 tuple 而不是生成器表达式?它使阅读变得稍微困难​​(需要跟踪更多的括号/括号/等),并且在大型情况下会浪费内存,而在小型情况下 2.x 的性能优势几乎无关紧要。
    • @abarnert 你说得对,性能是我有时更喜欢列表理解而不是生成器表达式的唯一原因。这是我从注重性能的编程比赛中养成的一个坏习惯。
    • 不可能:x if x else "" 吗?
    • @dansalmo:这取决于用例。跳过'' 与打印'' 显然没有区别,但如果你得到0False[],你也想跳过这些吗?
    • @AshwiniChaudhary:“性能很重要”是一回事; “猜测他们会给我什么样的数据,这样我就知道是否要编写在小输入上快 3% 但在大输入上慢 300% 的代码”,这似乎是在测试编程以外的东西。 (尽管在现实世界中您仍然需要擅长某些事情,尤其是如果您曾与“业务分析师”一起工作!)
    【解决方案2】:

    试试 zip 之类的功能

    >>> a = ("string1","string2","string3","string4","string5","string6","string7")
    >>> b = ("another string1","another string2",3,None,"another string5",6,7)
    >>> [str(x)+str(y) for x,y in zip(a,b)]
    ['string1another string1', 'string2another string2', 'string33', 'string4None', 'string5another string5', 'string66', 'string77']
    

    如果你希望结果是元组,你可以这样做:

    >>> tuple([str(x)+str(y) for x,y in zip(a,b)])
    ('string1another string1', 'string2another string2', 'string33', 'string4None', 'string5another string5', 'string66', 'string77')
    

    【讨论】:

    • 这几乎是对的,但"string4" + NoneTypeError,而不是"string4None"。 (如果你解决了这个问题,这与 Ashwini Chaudhary 之前的回答有何不同?)
    • @abarnert 提问者说“string4None”没问题。在连接两个部分之前,我使用了 str() 函数。所以它应该运作良好。
    猜你喜欢
    • 2012-11-19
    • 2021-07-16
    • 1970-01-01
    • 2014-06-16
    • 2013-07-09
    • 1970-01-01
    • 2019-08-30
    • 2011-06-02
    相关资源
    最近更新 更多