Hướng dẫn python int list
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of strings to integers is quite common in the development domain. Let’s discuss a few ways to solve this particular problem. Show Nội dung chính
Method 1: Using eval()Python eval() function parse the expression argument and evaluate it as a python expression and runs Python expression(code), If the expression is an int representation, Python converts the argument to an integer. Python3
Output: Modified list is: [1, -4, 3, -6, 7] Method 2: Naive MethodThis is the most generic method that strikes any programmer while performing this kind of operation. Just looping over the whole list and converting each string of the list to int by type casting. Python3
Output: Modified list is: [1, 4, 3, 6, 7] Method 3: Using list comprehensionThis is just a kind of replica of the above method, just implemented using list comprehension, a kind of shorthand that a developer looks for always. It saves the time and complexity of coding a solution. Python3
Output: Modified list is : [1, 4, 3, 6, 7] Method 4: Using map()This is the most elegant, pythonic, and recommended method to perform this particular task. This function is exclusively made for this kind of task and should be used to perform them. Python3
Output: Modified list is : [1, 4, 3, 6, 7] Method 5: List of strings with mixed integer representationsHere, we will first convert each string to a float first and then we will convert it into an integer by using the round() function, otherwise, it will through error. Python3
Output: Modified list is: [1, 4, 4, 7, 7] Given a list of integers, write a Python program to convert the given list into a single integer. Examples: Input : [1, 2, 3] Output : 123 Input : [55, 32, 890] Output : 5532890 There are multiple approaches possible to convert the given list into a single integer. Let’s see each one by one. Approach #1 : Naive Method
Output: 121517 Use the
Output: 123 Another approach to convert a list of multiple integers into a single integer is to use
Output: 123 A more mathematical way, which does not require to convert the integer list to string list is, to multiply each integer element with its corresponding power of 10, and then summing it up. It takes a time complexity of
Output: 123 A small variation to this program leads to less computation in calculation of sum, i.e. using
|