Python | Преобразовать кортеж в целое число
Иногда при работе с записями у нас может возникнуть проблема, когда нам нужно преобразовать записи данных в целые числа, присоединив их. Давайте обсудим некоторые способы выполнения этой задачи.
Method #1 : Using reduce()
+ lambda
The combination of above functions can be used to perform this task. In this, we use lambda function to perform logic of conversion and reduce performs task of iteration and combining result.
# Python3 code to demonstrate working of # Convert Tuple to integer # Using reduce() + lambda import functools # initialize tuple test_tuple = ( 1 , 4 , 5 ) # printing original tuple print ( "The original tuple : " + str (test_tuple)) # Convert Tuple to integer # Using reduce() + lambda res = functools. reduce ( lambda sub, ele: sub * 10 + ele, test_tuple) # printing result print ( "Tuple to integer conversion : " + str (res)) |
The original tuple : (1, 4, 5) Tuple to integer conversion : 145
Method #2 : Using int() + join() + map()
The combination of these functions can also be used to perform this task. In this, we convert each element to string using join() and iterate using map(). At last we perform integer conversion.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.