gpt4 book ai didi

python - 使用正则表达式转换列表

转载 作者:太空狗 更新时间:2023-10-29 21:45:32 25 4
gpt4 key购买 nike

我有一个包含这种形式的元素的列表,字符串可能会改变但格式保持相似:

["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem6"]

我想将其转换为下面的列表。您可以看到它会删除相同出现的字符串的副本,例如 Eth - 在新列表中只出现一次并将数字转换为 x 和 y 以更通用:

["RadioX","TetherX","SerialX/Y","EthX/Y","vlanX","modemX"]

我在搞乱不同的正则表达式,我的方法很乱,会对你们想到的任何优雅的解决方案感兴趣。

这里有一些可以改进的代码,同时 set 不保留顺序,所以也应该改进:

a = ["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth0/2","Eth1/0","vlanX","modem0","modem1","modem2","modem3","modem6"]
c =[]
for i in a:
b = re.split("[0-9]", i)
if "/" in i:
c.append(b[0]+"X/Y")
elif len(b) > 1:
c.append(b[0]+"X")
else:
c.append(b)
print set(c)

set(['modemX', 'TetherX', 'RadioX', 'vlanX', 'SerialX/Y', 'EthX/Y'])

为了保持顺序可能对集合进行的改进:

unique=[]
[unique.append(item) for item in c if item not in unique]
print unique

['RadioX', 'TetherX', 'SerialX/Y', 'EthX/Y', 'vlanX', 'modemX']

最佳答案

下面的代码应该足够通用以允许字符串中最多 3 个数字,但您可以简单地更改 repl 变量以允许更多。

import re

elements = ["Radio0","Tether0","Serial0/0","Eth0/0","Eth0/1","Eth1/0","Eth1/1","vlanX","modem0","modem1","modem2","modem3","modem6"]
repl = "XYZ"

for i in range(len(repl)):
elements = [re.sub("[0-9]",repl[i], element, 1) for element in elements]

result = set(elements)

关于python - 使用正则表达式转换列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38875489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com