简体   繁体   English

Python - 在数组内拆分字符串

[英]Python - split strings inside array

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 :迭代输入列表并使用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).对于输入列表中的每个条目,我们在一些 output 列表(最初为空)上调用extend This will add each element from splitting eg "5 6 7" as a new separate entry in the output list.这将添加来自拆分的每个元素,例如"5 6 7"作为 output 列表中的新单独条目。

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:解释:

  1. Join all strings into one string -> "123 45 6 78"将所有字符串连接成一个字符串 -> "123 45 6 78"
  2. Remove any white spaces -> "12345678"删除所有空格-> "12345678"
  3. Split each character -> ['1', '2', '3', '4', '5', '6', '7', '8']拆分每个字符 -> ['1', '2', '3', '4', '5', '6', '7', '8']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM