gpt4 book ai didi

python - 将两个元组合并为一个

转载 作者:太空宇宙 更新时间:2023-11-03 15:20:05 25 4
gpt4 key购买 nike

我有两个元组

("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 新手,所以我不确定该怎么做。组合这两个元组的最佳方法是什么?

最佳答案

使用 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 ""
''

关于python - 将两个元组合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16368068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com