简体   繁体   中英

How to turn one list element in two?

lets say i have a list like this:

bla = ['3,00 € 3,50 €\r\n', '3,00 €\r\n', '6,50 €\t5,50 €\r\n']

Every time I have two prices in one item I want to turn this item in two Items. So it looks like this:

['3,00 €', '3,50 €', '3,00 €', '6,50 €', '5,50 €']

Extract all prices matching the <digits>,<digits> € pattern with a regular expression and flatten the result list:

import re
l = [item for s in [re.findall("[0-9]+,[0-9]+\s?€", x) for x in bla] for item in s]

Edit:

Even shorter, join your list to a single string and extract all the strings matching said pattern:

l = re.findall("[0-9]+,[0-9]+\s?€", " ".join(bla))

Without regex: Split according to euro sign and reformat, flattening the list in the process, and stripping all blanks:

bla = ['3,00 € 3,50 €\r\n', '3,00 €\r\n', '6,50 €\t5,50 €\r\n']

result = ["{} {}".format(x.strip(),"€") for item in bla for x in item.split("€") if x.strip()]

print(result)

result:

['3,00 €', '3,50 €', '3,00 €', '6,50 €', '5,50 €']

Here's (yet another) way to do it without regular expressions:

from itertools import chain

bla = ['3,00 € 3,50 €\v\n', '3,00 €\v\n', '6,50 €\t5,50 €\v\n']

result = [r for r in chain.from_iterable(((v+' €' for v in (y.strip()
                                                    for y in s.split('€') if y.strip()))
                                                        for s in bla))]
print(result)

Output:

['3,00 €', '3,50 €', '3,00 €', '6,50 €', '5,50 €']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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