Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Reform K digit elements
When working with lists of numbers, you may need to reform K digit elements by concatenating all numbers into a string and then splitting them into chunks of K digits. This technique uses string manipulation and list comprehension.
Example
Below is a demonstration of reforming elements into 3-digit chunks ?
my_list = [231, 67, 232, 1, 238, 31, 793]
print("The list is :")
print(my_list)
K = 3
print("The value of K is")
print(K)
# Join all numbers as a single string
temp = ''.join([str(ele) for ele in my_list])
print("Combined string:", temp)
my_result = []
# Split into K-digit chunks
for index in range(0, len(temp), K):
chunk = temp[index: index + K]
if chunk: # Only add non-empty chunks
my_result.append(int(chunk))
print("The resultant list is :")
print(my_result)
The list is : [231, 67, 232, 1, 238, 31, 793] The value of K is 3 Combined string: 2316723212383179 The resultant list is : [231, 672, 321, 238, 317, 9]
How It Works
The algorithm follows these steps:
- Concatenation: All list elements are converted to strings and joined together
- Chunking: The combined string is split into K-digit segments
- Conversion: Each chunk is converted back to integer and added to result
Alternative Using List Comprehension
Here's a more concise approach using list comprehension ?
my_list = [231, 67, 232, 1, 238, 31, 793]
K = 3
# One-liner approach
temp = ''.join([str(ele) for ele in my_list])
result = [int(temp[i:i+K]) for i in range(0, len(temp), K) if temp[i:i+K]]
print("Original list:", my_list)
print("Reformed list:", result)
Original list: [231, 67, 232, 1, 238, 31, 793] Reformed list: [231, 672, 321, 238, 317, 9]
Conclusion
Reforming K digit elements involves concatenating all numbers into a string and splitting into fixed-size chunks. This technique is useful for data restructuring and number manipulation tasks.
Advertisements
