0

这很难解释,但这是我的问题..

sampleList = ['_ This is an item.','__ This is also an item']

我正在尝试获取 sampleList 并查找是否_仅在第一个字符行中出现,将其替换为#,然后如果__出现,则替换为&

即使对我自己来说,也有点难以理解。

基本上,如果我有一个列表,我希望它通过列表工作,只找到可能的 dict 的第一个实例并将其替换为相应的值。然后返回整个列表..

编辑:

对不起,如果我描述的不够充分..

dictarray = {
'_':'&',
'__':'*#',
'____':'*$(@'
}

sampleList = ['_ This is an item.','__ This is also an item','_ just another _ item','____ and this last one']

输出:

sampleList = ['& This is an item.','*# This is also an item','& just another _ item','*$(@ and this last one']

如果在项目的开头找到密钥,我需要能够捕获,如果是这样,请将其更改为值。

4

2 回答 2

5
# The original input data
dictarray = {
'_':'&',
'__':'*#',
'____':'*$(@'
}

sampleList = ['_ This is an item.','__ This is also an item','_ just another _ item','____ and this last one']

# Order the substitutions so the longest are first.
subs = sorted(dictarray.items(), key=lambda pair: len(pair[0]), reverse=True)

def replace_first(s, subs):
    """Replace the prefix of `s` that first appears in `subs`."""
    for old, new in subs:
        if s.startswith(old):
            # replace takes a count of the number of replacements to do.
            return s.replace(old, new, 1)
    return s

# make a new list by replace_first'ing all the strings.
new_list = [replace_first(s, subs) for s in sampleList]

print new_list

产生:

['& This is an item.', '*# This is also an item', '& just another _ item', '*$(@ and this last one']

在这里,我已经对 dictarray 进行了按摩,以首先订购最长的替换,因此较短的前缀不会排除较长的前缀。

于 2012-09-11T02:12:28.980 回答
1

这里的诀窍是将较长的下划线 ( __) 放在if条件中,然后将较小的下划线 ()_放在elif条件中:

dic = {
'_':'&',
'__':'*#',
'____':'*$(@'
}
lis=['_ This is an item.','__ This is also an item','_ just another _ item','____ and this last one']
for x in sorted(dic,key=len,reverse=True):
    for i,y in enumerate(lis):
        if y.startswith(x):
            lis[i]=y.replace(x,dic[x])

print(lis)

输出:

['& This is an item.', '*# This is also an item', '& just another & item', '*$(@ and this last one']
于 2012-09-11T02:01:49.473 回答