Python | Кумулятивный продукт столбца вложенного кортежа

Опубликовано: 12 Апреля, 2022

Иногда, работая с записями, мы можем столкнуться с проблемой, когда нам нужно выполнить умножение элементов кортежа по индексу. Это может усложниться, если элементы кортежа будут кортежами, а внутренние элементы снова будут кортежами. Давайте обсудим некоторые способы решения этой проблемы.

Method #1 : Using zip() + nested generator expression
The combination of above functions can be used to perform the task. In this, we combine the elements across tuples using zip(). The iterations and product logic is provided by generator expression.

# Python3 code to demonstrate working of
# Cummulative Nested Tuple Column Product
# using zip() + nested generator expression
  
# initialize tuples
test_tup1 = ((1, 3), (4, 5), (2, 9), (1, 10))
test_tup2 = ((6, 7), (3, 9), (1, 1), (7, 3))
  
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Cummulative Nested Tuple Column Product
# using zip() + nested generator expression
res = tuple(tuple(a * b for a, b in zip(tup1, tup2))
    for tup1, tup2 in zip(test_tup1, test_tup2))
  
# printing result
print("The resultant tuple after product : " + str(res))
Output :
The original tuple 1 : ((1, 3), (4, 5), (2, 9), (1, 10))
The original tuple 2 : ((6, 7), (3, 9), (1, 1), (7, 3))
The resultant tuple after product : ((6, 21), (12, 45), (2, 9), (7, 30))

Method #2 : Using isinstance() + zip() + loop + list comprehension
The combination of above functions can be used to perform this particular task. In this, we check for the nesting type and perform recursion. This method can give flexibility of more than 1 level nesting.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.