简体   繁体   English

如何将列表元素一分为二?

[英]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: 使用正则表达式提取与<digits>,<digits> €模式匹配的所有价格<digits>,<digits> €并将结果列表展平:

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 €']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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