Python – Reform K digit elements
Last Updated :
04 May, 2023
Given the Python list, reform the element to have K digits in a single element.
Input : test_list = [223, 67, 332, 1, 239, 2, 931], K = 2
Output : [22, 36, 73, 32, 12, 39, 29, 31]
Explanation : Elements reformed to assign 2 digits to each element.
Input : test_list = [223, 67, 3327], K = 3
Output : [223, 673, 327]
Explanation : Elements reformed to assign 3 digits to each element.
Method #1 : Using slicing + join() + loop
In this, we perform the task of joining all elements to a single string, then slice K digits, and reconvert to a list.
Python3
test_list = [ 223 , 67 , 332 , 1 , 239 , 2 , 931 ]
print ( "The original list is : " + str (test_list))
K = 2
temp = ''.join([ str (ele) for ele in test_list])
res = []
for idx in range ( 0 , len (temp), K):
res.append( int (temp[idx: idx + K]))
print ( "Reforming K digits : " + str (res))
|
Output
The original list is : [223, 67, 332, 1, 239, 2, 931]
Reforming K digits : [22, 36, 73, 32, 12, 39, 29, 31]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using list comprehension + join()
In this, the task of reforming the list is done using list comprehension.
Python3
test_list = [ 223 , 67 , 332 , 1 , 239 , 2 , 931 ]
print ( "The original list is : " + str (test_list))
K = 2
temp = ''.join([ str (ele) for ele in test_list])
res = [ int (temp[idx: idx + K]) for idx in range ( 0 , len (temp), K)]
print ( "Reforming K digits : " + str (res))
|
Output
The original list is : [223, 67, 332, 1, 239, 2, 931]
Reforming K digits : [22, 36, 73, 32, 12, 39, 29, 31]
Time Complexity: O(N), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(N), where n is the number of elements in the list “test_list”.
Method #4: Using itertools and string concatenation
- Import the ‘itertools’ module.
- Convert each element of the original list to a string and concatenate it to a variable ‘temp’.
- Using the ‘grouper’ function from itertools, group ‘temp’ into groups of K.
- For each group, join the characters using the ‘join’ function and append the integer value of the resulting string to ‘res’.
- Print the final ‘res’ list.
Python3
import itertools
test_list = [ 223 , 67 , 332 , 1 , 239 , 2 , 931 ]
print ( "The original list is : " + str (test_list))
K = 2
temp = "".join( str (ele) for ele in test_list)
res = [ int (" ".join(group)) for group in itertools.zip_longest(*[iter(temp)]*K, fillvalue=" ")]
print ( "Reforming K digits : " + str (res))
|
Output
The original list is : [223, 67, 332, 1, 239, 2, 931]
Reforming K digits : [22, 36, 73, 32, 12, 39, 29, 31]
Time complexity: O(N), where n is the length of the original list.
Auxiliary space: O(N), where n is the length of the original list (for storing the ‘temp’ string).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...