【问题标题】:How to transform nested strings in array to separated words?如何将数组中的嵌套字符串转换为单独的单词?
【发布时间】:2017-03-07 17:18:26
【问题描述】:

我正在尝试使用 Python 进行简单的数组和字符串转换,但我被卡住了。我有这个数组:

data = ['one, two, three',  'apple, pineapple',  'frog, rabbit, dog, cat, horse'] 

我想得到这个结果:

new_data = ['one', 'two', 'three', 'apple', 'pineapple', 'frog', 'rabbit', 'dog', 'cat', 'horse']

这就是我正在做的,但每当我使用时

data_to_string = ''.join(data) 
new_data = re.findall(r"[\w']+", data_to_string)

它给了我这个:

['one', 'two', 'threeapple', 'pineapplefrog', 'rabbit', 'dog', 'cat', 'horse']

你可以看到“threeapple”和“pineapplefrog”没有分开,我怎样才能避免这个问题?

【问题讨论】:

    标签: python arrays string


    【解决方案1】:

    查看列表推导,它们很棒。

    这是你的答案:

    [word for string in data for word in string.split(", ")]
    

    【讨论】:

    • 我会检查列表理解然后:)
    【解决方案2】:

    一些简单的列表理解和字符串方法怎么样? re 对此太过分了。

    >>> data = ['one, two, three',  'apple, pineapple',  'frog, rabbit, dog, cat, horse']
    >>> [word.strip() for string in data for word in string.split(',')]
    ['one', 'two', 'three', 'apple', 'pineapple', 'frog', 'rabbit', 'dog', 'cat', 'horse']
    

    【讨论】:

      【解决方案3】:

      使用连接和拆分

      ','.join(data).split(',')
      

      结果

      ['one',
       ' two',
       ' three',
       'apple',
       ' pineapple',
       'frog',
       ' rabbit',
       ' dog',
       ' cat',
       ' horse']
      

      【讨论】:

      • 其他答案也是正确的。但是如果您有像 data*10 这样的大型数组,那么您将获得性能优势 join 和 split 命令。 % timeit ','.join(data*10).split(',') 100000 次循环,最好的 3:每个循环 10.3 µs %timeit [word.strip() for string in data*10 for word in string.split (',')] 10000 次循环,最好的 3 次:每个循环 42.4 µs。没什么大不了的,但想分享一下。
      猜你喜欢
      • 1970-01-01
      • 2016-02-04
      • 2016-05-22
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      相关资源
      最近更新 更多