0

试图以正确的形式在我的列表中获取所有匹配项。例子:

import re

regex = re.compile(r'(\d{1,4})')
text = ['(261, 264)', '(458, 393)', '(960, 540)', '(542, 424)', '(541, 424)']
print(regex.findall(text[0]))
print(list(filter(regex.findall, text)))

输出:

['261', '264']
['(261, 264)', '(458, 393)', '(960, 540)', '(542, 424)', '(541, 424)']

我试图让底部的格式与顶部的格式相同(不带括号或逗号)。这可能吗?我似乎无法让这些函数返回列表中的所有匹配项(如果可能的话,我想像 list(filter()) 一样将它放在 1 行中)

编辑::所需的输出:

['261', '264', '458', '393', '960', '540', '542', '424', '542', '424']
4

3 回答 3

0

试试这个:

import re

regex = re.compile(r'(\d{1,4})')
text = ['(261, 264)', '(458, 393)', '(960, 540)', '(542, 424)', '(541, 424)']
print(regex.findall(text[0]))
print([elem for tup in map(regex.findall, text) for elem in tup])
于 2020-07-15T01:23:36.547 回答
0

合并所有匹配的列表理解(通过迭代所有匹配):

import re

regex = re.compile(r'(\d{1,4})')
text = ['(261, 264)', '(458, 393)', '(960, 540)', '(542, 424)', '(541, 424)']

print([x for t in text for x in regex.findall(t)])
于 2020-07-15T01:23:53.593 回答
0

这是我的解决方案:

解释

  1. 查找列表中每个元素的匹配项(就像您所做的那样)

这将为您提供以下结果:

[['261', '264'],
 ['458', '393'],
 ['960', '540'],
 ['542', '424'],
 ['541', '424']]
  1. 展平此列表:

这会给你留下你想要的结果

['261', '264', '458', '393', '960', '540', '542', '424', '541', '424']

最终代码

import itertools
import re

original_list =  ['(261, 264)', '(458, 393)', '(960, 540)', '(542, 424)', '(541, 424)']
regex =  re.compile(r"\d\d\d")


matches_per_element = [regex.findall(txt) for txt in original_list]
flattened_list = list(itertools.chain(*matches_per_element))


### Display the result
print(flattened_list)
>>> ['261', '264', '458', '393', '960', '540', '542', '424', '541', '424']

于 2020-07-15T01:54:54.737 回答