[英]How to split list element into two?
如果我將數據存儲在列表中,例如
images = ['pdf-one','gif-two','jpg-three']
如何在連字符處將這些元素拆分為多個元素 - 而不是子列表。 即
images = ['pdf','-one','gif','-two','jpg','-three']
不
images = [['pdf','-one'],['gif','-two'],['jpg','-three']]
在這種情況下,使用正則表達式進行拆分可以獲得最易讀的代碼:
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']
您可以使用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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.