简体   繁体   English

在 Python 中,如何根据特定的字符串格式删除列表中的项目?

[英]In Python, how to remove items in a list based on the specific string format?

I have a Python list as below:我有一个 Python 列表如下:

merged_cells_lst = [
'P19:Q19
'P20:Q20
'P21:Q21
'P22:Q22
'P23:Q23
'P14:Q14
'P15:Q15
'P16:Q16
'P17:Q17
'P18:Q18
'AU9:AV9
'P10:Q10
'P11:Q11
'P12:Q12
'P13:Q13
'A6:P6
'A7:P7
'D9:AJ9
'AK9:AQ9
'AR9:AT9'
'A1:P1'
]

I only want to unmerge the cells in the P and Q columns.我只想取消合并 P 和 Q 列中的单元格。 Therefore, I seek to remove any strings/items in the merged_cells_lst that does not have the format "P##:Q##" .因此,我试图删除 merge_cells_lst 中不具有"P##:Q##"格式的任何字符串/项目。

I think that regex is the best and most simple way to go about this.我认为正则表达式是解决这个问题的最好和最简单的方法。 So far I have the following:到目前为止,我有以下内容:

for item in merge_cell_lst:
    if re.match(r'P*:Q*'):
            pass
    else:
            merged_cell_lst.pop(item)

print(merge_cell_lst)

The code however is not working.但是代码不起作用。 I could use any additional tips/help.我可以使用任何其他提示/帮助。 Thank you!谢谢!

Modifying a list while looping over it causes troubles.在循环遍历列表时修改列表会导致麻烦。 You can use list comprehension instead to create a new list.您可以改用列表推导来创建一个新列表。

Also, you need a different regex expression.此外,您需要不同的正则表达式。 The current pattern P*:Q* matches PP:QQQ , :Q , or even : , but not P19:Q19 .当前模式P*:Q*匹配PP:QQQ:Q甚至: ,但匹配P19:Q19

import re

merged_cells_lst = ['P19:Q19', 'P20:Q20', 'P21:Q21', 'P22:Q22', 'P23:Q23', 'P14:Q14', 'P15:Q15', 'P16:Q16', 'P17:Q17', 'P18:Q18', 'AU9:AV9', 'P10:Q10', 'P11:Q11', 'P12:Q12', 'P13:Q13', 'A6:P6', 'A7:P7', 'D9:AJ9', 'AK9:AQ9', 'AR9:AT9', 'A1:P1']

p = re.compile(r"P\d+:Q\d+")

output = [x for x in merged_cells_lst if p.match(x)]
print(output)
# ['P19:Q19', 'P20:Q20', 'P21:Q21', 'P22:Q22', 'P23:Q23', 'P14:Q14', 'P15:Q15',
#  'P16:Q16', 'P17:Q17', 'P18:Q18', 'P10:Q10', 'P11:Q11', 'P12:Q12', 'P13:Q13']

Your list has some typos, should look something like this:您的列表有一些拼写错误,应如下所示:

merged_cells_lst = [ 'P19:Q19', 'P20:Q20', 'P21:Q21', ...] merge_cells_lst = ['P19:Q19', 'P20:Q20', 'P21:Q21', ...]

Then something as simple as:然后一些简单的事情:

x = [k for k in merged_cells_lst if k[0] == 'P']

would work.会工作。 This is assuming that you know a priori that the pattern you want to remove follows the Pxx:Qxx format.这是假设您先验地知道要删除的模式遵循 Pxx:Qxx 格式。 If you want a dynamic solution then you can replace the condition in the list comprehension with a regex match.如果您想要一个动态解决方案,那么您可以用正则表达式匹配替换列表理解中的条件。

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

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