📜  Python|块元组到 N

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

Python|块元组到 N

有时,在处理数据时,我们可能会遇到一个问题,即我们可能需要对每个大小为 N 的元组执行分块。这在我们需要以块的形式提供数据的应用程序中很流行。让我们讨论可以执行此任务的某些方式。

方法#1:使用列表理解
这是执行此任务的粗略和速记方法。在这里,我们一次拆分 N 个元素并为它们构造一个新的元组。

Python3
# Python3 code to demonstrate working of
# Chunk Tuples to N
# using list comprehension
  
# initialize tuple
test_tup = (10, 4, 5, 6, 7, 6, 8, 3, 4)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# initialize N 
N = 3
  
# Chunk Tuples to N
# using list comprehension
res = [test_tup[i : i + N] for i in range(0, len(test_tup), N)]
  
# printing result
print("The tuples after chunking are : " + str(res))


Python3
# Python3 code to demonstrate working of
# Chunk Tuples to N
# using zip() + iter()
  
# initialize tuple
test_tup = (10, 4, 5, 6, 7, 6, 8, 3, 4)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# initialize N 
N = 3
  
# Chunk Tuples to N
# using zip() + iter()
temp = [iter(test_tup)] * N
res = list(zip(*temp))
  
# printing result
print("The tuples after chunking are : " + str(res))


输出 :
The original tuple : (10, 4, 5, 6, 7, 6, 8, 3, 4)
The tuples after chunking are : [(10, 4, 5), (6, 7, 6), (8, 3, 4)]

方法#2:使用zip() + iter()
上述功能的组合也可以用来解决这个问题。在此,我们使用 zip() 来组合块,并使用 iter() 转换为合适的格式。

Python3

# Python3 code to demonstrate working of
# Chunk Tuples to N
# using zip() + iter()
  
# initialize tuple
test_tup = (10, 4, 5, 6, 7, 6, 8, 3, 4)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# initialize N 
N = 3
  
# Chunk Tuples to N
# using zip() + iter()
temp = [iter(test_tup)] * N
res = list(zip(*temp))
  
# printing result
print("The tuples after chunking are : " + str(res))
输出 :
The original tuple : (10, 4, 5, 6, 7, 6, 8, 3, 4)
The tuples after chunking are : [(10, 4, 5), (6, 7, 6), (8, 3, 4)]