gpt4 book ai didi

python - 从两个单独的元组开始,如何创建一个非嵌套元组?

转载 作者:行者123 更新时间:2023-11-28 20:45:19 24 4
gpt4 key购买 nike

假设我有两个元组:

tuple1 = ("a", "b", "c")
tuple2 = ("y", "z")

我想返回一个元组:

return_tuple == ("a", "b", "c", "y", "z")

这里我面临的挑战是元组是不可变的,所以我不能简单地将 tuple2 附加到 tuple1。我知道我可以将两者都转换为列表,然后再转换回元组,但我不想这样做(除非我必须这样做)。

我也试过这样做:

return_tuple = ("a", "b", "c", sum(tuple2, ()))

这不起作用,因为:

TypeError: can only concatenate tuple (not "str") to tuple.

是否有一种干净、pythonic 和漂亮的方法来实现它?

最佳答案

只需将元组与 + 运算符相加即可:

>>> tuple1 = ("a", "b", "c")
>>> tuple2 = ("y", "z")
>>> tuple1 + tuple2 # This creates a new tuple object
('a', 'b', 'c', 'y', 'z')
>>> tuple1 # tuple1 is unaffected
('a', 'b', 'c')
>>> tuple2 # tuple2 is also unaffected
('y', 'z')
>>>

请注意,您可以对字符串和列表执行相同的操作:

>>> s1 = "a"
>>> s2 = "b"
>>> s1 + s2
'ab'
>>> s1
'a'
>>> s2
'b'
>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> l1 + l2
[1, 2, 3, 4, 5, 6]
>>> l1
[1, 2, 3]
>>> l2
[4, 5, 6]
>>>

关于python - 从两个单独的元组开始,如何创建一个非嵌套元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23838535/

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