在Python中从列表中删除字符

2024-04-26 03:53:01 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我试图打印出我们实验室中的VMWare模板列表。我希望输出如下所示:

vagrant-ubuntu12.04-small
vagrant-centos6.6-small
vagrant-ubuntu12.04
vagrant-centos6.6

而电流输出看起来更像这样:

['[datastore2] vagrant-ubuntu12.04-small']
['[datastore2] vagrant-centos6.6-small']
['[datastore1] vagrant-centos6.6']
['[datastore1] vagrant-ubuntu12.04']

这是我的密码:

from pysphere import VIServer
from pprint import pprint

VSPHERE = VIServer()

VSPHERE.connect('helike.labs.sdelements.com',
                'xxxxxxxxx',
                'xxxxxxxxx')

VMLIST = VSPHERE.get_registered_vms()


def is_template(string):
    """ Is it a template? """
    if string.find(".vmtx") == -1:
        return False
    else:
        return True


def is_vagrant_template(string):
    """ Is it a Vagrant Template? """
    if string.find("vagrant") == -1:
        return False
    else:
        return True


def is_proper_template(string):
    """ filter out extraneous templates """
    if string.find("sde") == -1:
        return True
    else:
        return False

temp1 = filter(is_template, VMLIST)
temp2 = filter(is_vagrant_template, temp1)
temp3 = filter(is_proper_template, temp2)

for item in temp3:
    relist = item.split('/')[:1]
    pprint(relist)

我知道这可能是非常业余的代码,但我不是一个真正的python人。有没有什么正则表达式或者什么我可以用来清理一下的?你知道吗


Tags: falsetruestringreturnifisdeftemplate
3条回答

如果总是相同的格式,只需在空白处拆分一次并提取第二个元素:

data = [['[datastore2] vagrant-ubuntu12.04-small'],
['[datastore2] vagrant-centos6.6-small'],
['[datastore1] vagrant-centos6.6'],
['[datastore1] vagrant-ubuntu12.04']]


for sub in data:
    print(sub[0].split(None,1)[1])

vagrant-ubuntu12.04-small
vagrant-centos6.6-small
vagrant-centos6.6
vagrant-ubuntu12.04

您也可以在将数据放入列表之前进行拆分,但如果看不到实际输入,则无法确定。你知道吗

您要查找的函数是maphttps://docs.python.org/2/library/functions.html#map

您要做的是在filter之后调用map,如下所示:

def is_proper_vagrant_template(string):
    """ Is it a proper Vagrant template? """
    return ".vmtx" in string and "vagrant" in string and "sde" not in string

def clean_template(string):
    """ Return the second half of the string, assuming whitespace as a separator """
    return string.split()[1]

temp1 = filter(is_proper_vagrant_template, VMLIST)
clean = map(clean_template, temp1)

在上面的代码片段中,filter的工作方式与您之前的工作方式相同,只是我重写了调用,将您的三个函数合并为一个。map函数获取过滤后的列表,并对每个元素调用clean_template,将结果作为列表返回。你知道吗

clean_template返回字符串的后半部分(您感兴趣的部分),假设字符串中除了您标识的内容外没有其他空格。你知道吗

一个简单的正则表达式就可以做到这一点,提供了一些灵活性。
可以将捕获组1抓取到一个数组中,
或者只是全局查找并替换为捕获组1。
如果您不知道所有可能的字符,只需替换
[a-z\d.-]+\S+

(?mi)^\['\[[^\]]*\]\h+([a-z\d.-]+)\h*'\]

 (?mi)                         # Modes: Multi-line, No-Case
 ^                             # BOL
 \[' \[ [^\]]* \]
 \h+ 
 ( [a-z\d.-]+ )                # (1)
 \h* 
 '\]

相关问题 更多 >