📜  Python|重复元组 N 次

📅  最后修改于: 2022-05-13 01:55:43.569000             🧑  作者: Mango

Python|重复元组 N 次

有时,在处理数据时,我们可能会遇到需要复制的问题,即构造元组的副本。这是计算机编程的许多领域中的重要应用。让我们讨论可以执行此任务的某些方式。

方法 #1:使用* operator
乘法运算符可用于构造容器的副本。即使元组是不可变的,这也可以扩展到元组。

# Python3 code to demonstrate working of
# Repeating tuples N times
# using * operator
  
# initialize tuple 
test_tup = (1, 3)
  
# printing original tuple 
print("The original tuple : " + str(test_tup))
  
# initialize N 
N = 4
  
# Repeating tuples N times
# using * operator
res = ((test_tup, ) * N)
  
# printing result
print("The duplicated tuple elements are : " + str(res))
输出 :
The original tuple : (1, 3)
The duplicated tuple elements are : ((1, 3), (1, 3), (1, 3), (1, 3))

方法#2:使用repeat()
itertools库的内部函数repeat()可以用来实现上述问题的解决。

# Python3 code to demonstrate working of
# Repeating tuples N times
# using repeat()
from itertools import repeat
  
# initialize tuple 
test_tup = (1, 3)
  
# printing original tuple 
print("The original tuple : " + str(test_tup))
  
# initialize N 
N = 4
  
# Repeating tuples N times
# using repeat()
res = tuple(repeat(test_tup, N))
  
# printing result
print("The duplicated tuple elements are : " + str(res))
输出 :
The original tuple : (1, 3)
The duplicated tuple elements are : ((1, 3), (1, 3), (1, 3), (1, 3))