I have an array that looks something like this:
arr1 = ["1", "2", "3 4", "5 6 7", "8"]
and I want to, somehow, split the strings with spaces in them turning this array into this:
split_arr1 = ["1", "2", "3", "4", "5", "6", "7", "8"]
Note: The split array does not have to be in order
Thank you!
Iterating the input list and using split
:
arr1 = ["1", "2", "3 4", "5 6 7", "8"]
output = []
for item in arr1:
output.extend(item.split())
print(output) # ['1', '2', '3', '4', '5', '6', '7', '8']
For each entry in the input list we call extend
on some output list (initially empty). This will add each element from splitting eg "5 6 7"
as a new separate entry in the output list.
You could do this using nested list comprehension:
arr1 = ["1", "2", "3 4", "5 6 7", "8"]
split_arr1 = [split_item for item in arr1 for split_item in item.split()]
# ['1', '2', '3', '4', '5', '6', '7', '8']
A very simple solution:
arr1 = ["1", "2", "3 4", "5 6 7", "8"]
split_arr1 = list("".join(arr1).replace(" ", ""))
Explanation:
"123 45 6 78"
"12345678"
['1', '2', '3', '4', '5', '6', '7', '8']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.