Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split list element into two?

If I have data stored in a list, e.g.

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

How do I split these into multiple elements at the hyphen - not sublists. I.e.

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

not

images = [['pdf','-one'],['gif','-two'],['jpg','-three']]
like image 911
Hayley van Waas Avatar asked Feb 08 '14 10:02

Hayley van Waas


People also ask

How do you split elements in a list in Python?

Create an empty list that will store the quotients. Iterate across all the elements in the given list using a for loop. Divide each element with the given number/divisor and append the result in the resultant list. Finally, display the resultant list after all the quotients have been calculated and appended to it.

How do you separate items in a list?

Usually, we use a comma to separate three items or more in a list. However, if one or more of these items contain commas, then you should use a semicolon, instead of a comma, to separate the items and avoid potential confusion.

How do you cut a list in Python?

To trim in-place, use del on a slice; e.g. del listobj[-x:] will remove the last x elements from the list object.


1 Answers

In this case splitting with a regex makes for the most readable code:

import re

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

Demo:

>>> 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']
like image 132
Martijn Pieters Avatar answered Nov 15 '22 09:11

Martijn Pieters