如何将列表元素拆分为两个?

时间:2014-02-08 10:30:49

标签: python list sublist

如果我将数据存储在列表中,例如

images = ['pdf-one','gif-two','jpg-three']

如何将这些元素拆分为连字符中的多个元素 - 而不是子列表。即。

images = ['pdf','-one','gif','-two','jpg','-three']

images = [['pdf','-one'],['gif','-two'],['jpg','-three']]

2 个答案:

答案 0 :(得分:5)

在这种情况下,使用正则表达式进行拆分可以获得最易读的代码:

import re

hyphensplit = re.compile('(-[a-z]+)').split
images = [part for img in images for part in hyphensplit(img) if part]

演示:

>>> import re
>>> hyphensplit = re.compile('(-[a-z]+)').split
>>> images = ['pdf-one','gif-two','jpg-three']
>>> [part for img in images for part in hyphensplit(img) if part]
['pdf', '-one', 'gif', '-two', 'jpg', '-three']

答案 1 :(得分:4)

您可以使用str.partition

>>> from itertools import chain
>>> images = ['pdf-one', 'gif-two', 'jpg-three']
>>> list(chain.from_iterable([[a, b+c] for a, b, c 
                                            in (x.partition('-') for x in images)]))
['pdf', '-one', 'gif', '-two', 'jpg', '-three']

使用生成器函数获得更易读的解决方案:

def my_split(seq):
    for item in seq:
        a, b, c = item.partition('-')
        yield a
        yield b+c

>>> list(my_split(images))
['pdf', '-one', 'gif', '-two', 'jpg', '-three']