向元组添加元素的有效方法 [英] Efficient way to add elements to a tuple

查看:53
本文介绍了向元组添加元素的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向元组添加元素.我找到了 2 种方法.这个这个 回答说添加两个元组.它将创建一个新元组

I want to add elements to a tuple. I found 2 ways to do it. This and this answers say add two tuples. It will create a new tuple

a = (1,2,3)
b = a + (5,)

正如这个所说,将元组转换为列表,添加元素,然后将其转换回元组>

Where as this says, convert the tuple to list, add the element and then convert it back to tuple

a = (1,2,3)
tmp = list(a)
tmp.insert(3, 'foobar')
b = tuple(tmp)

这两者中哪个在内存和性能方面是高效的?
另外,假设我想在元组中间插入一个元素,是否可以使用第一种方法?
谢谢!

Which among these two is efficient in terms of memory and performance?
Also, suppose I want to insert an element in the middle of a tuple, is that possible using the first method?
Thanks!

推荐答案

如果你只添加一个元素,使用

If you are only adding a single element, use

a += (5, )

或者,

a = (*a, 5)

元组是不可变的,所以添加一个元素意味着你需要创建一个新的元组对象.我不建议强制转换为列表,除非您要在循环中添加许多元素等.

Tuples are immutable, so adding an element will mean you will need to create a new tuple object. I would not recommend casting to a list unless you are going to add many elements in a loop, or such.

a_list = list(a)
for elem in iterable:
    result = process(elem)
    a_list.append(result)

a = tuple(a_list)

<小时>

如果要在中间插入一个元素,可以使用:


If you want to insert an element in the middle, you can use:

m = len(a) // 2
a = (*a[:m], 5, *a[m:])

或者,

a = a[:m] + (5, ) + a[m:]

这篇关于向元组添加元素的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆