如何为元组增加价值?

2022-01-19 00:00:00 python tuples

问题描述

我正在编写一个脚本,其中有一个元组列表,例如 ('1','2','3','4').例如:

I'm working on a script where I have a list of tuples like ('1','2','3','4'). e.g.:

list = [('1','2','3','4'),
        ('2','3','4','5'),
        ('3','4','5','6'),
        ('4','5','6','7')]

现在我需要添加'1234''2345''3456''4567' 分别在每个元组的末尾.例如:

Now I need to add '1234', '2345','3456' and '4567' respectively at the end of each tuple. e.g:

list = [('1','2','3','4','1234'),
        ('2','3','4','5','2345'),
        ('3','4','5','6','3456'),
        ('4','5','6','7','4567')]

有没有可能?


解决方案

元组是不可变的,不应该改变——这就是列表类型的用途.

Tuples are immutable and not supposed to be changed - that is what the list type is for.

但是,您可以使用 originalTuple + (newElement,) 替换每个元组,从而创建一个新元组.例如:

However, you can replace each tuple using originalTuple + (newElement,), thus creating a new tuple. For example:

t = (1,2,3)
t = t + (1,)
print(t)
(1,2,3,1)

但我宁愿建议从头开始使用列表,因为它们插入项目的速度更快.

But I'd rather suggest to go with lists from the beginning, because they are faster for inserting items.

还有一个提示:不要覆盖程序中的内置名称 list,而是调用变量 l 或其他名称.如果覆盖内置名称,则不能在当前范围内再使用它.

And another hint: Do not overwrite the built-in name list in your program, rather call the variable l or some other name. If you overwrite the built-in name, you can't use it anymore in the current scope.

相关文章