从相似字符串列表中获取后缀

问题描述 投票:0回答:2
# code to get commonprefix
    def commonprefix(m):
        if not m: return ''
        s1 = min(m)
        s2 = max(m)
        for i, c in enumerate(s1):
            if c != s2[i]:
                return s1[:i]
        return s1
#code to get the different suffix 
    strList = map(str, objList)
    strList = map(lambda x: x.replace('', ''), strList)  

# My code to get the different suffix of each element of a list 

    for i in range(len(liste)):

        Listelement = liste[i]["title"].tolist()
        common_name = commonprefix(Listelement)
        try:
            strList = map(str, Listelement) 
            strList = map(lambda x: x.replace(common_name, ''), strList)
            print(Listelement)
        except:
            pass

# this is how my "Listelement" variable look like

    ['Le Coton Coton Extra Doux Boîte 100pce - CHANEL']
    ['Allure Eau De Toilette Vaporisateur 50ml - CHANEL', 'Allure Eau De Toilette Vaporisateur 100ml - CHANEL']
    ['Allure Eau De Toilette Vaporisateur 50ml - CHANEL', 'Allure Eau De Toilette Vaporisateur 100ml - CHANEL']
    ['Eau De Cologne Les Exclusifs De Chanel 75ml - CHANEL', 'Eau De Cologne Les Exclusifs De Chanel 200ml - CHANEL']
    ['Eau De Cologne Les Exclusifs De Chanel 75ml - CHANEL', 'Eau De Cologne Les Exclusifs De Chanel 200ml - CHANEL']

大家好,我在查找产品列表的后缀时遇到了一个小问题。我得到了公共前缀函数,它为我的列表提供了正确的答案,但是当我尝试删除每个列表的每个元素的 common_prefix 时,它不起作用,你知道为什么吗? 非常感谢你

python prefix suffix
2个回答
2
投票
  1. 您无需为
    os.path.commonprefix
    重新发明轮子。
  2. 此外,您可以在字符串上使用 slicing 语法,而不是逐一计算字符。

解决方案

import re
import os

ls = ['Allure Eau De Toilette Vaporisateur 50ml - CHANEL', 'Allure Eau De Toilette Vaporisateur 100ml - CHANEL']

# find common prefix
pfx = os.path.commonprefix(ls)
ans = [el[len(pfx):] for el in ls]
print(ans)  # ['50ml - CHANEL', '100ml - CHANEL']

0
投票
#!/usr/bin/env python3

# common prefix and common suffix of a list of strings
# https://stackoverflow.com/a/6719272/10440128
# https://codereview.stackexchange.com/a/145762/205605

import itertools

def all_equal(it):
    x0 = it[0]
    return all(x0 == x for x in it)

def common_prefix(strings):
    char_tuples = zip(*strings)
    prefix_tuples = itertools.takewhile(all_equal, char_tuples)
    return "".join(x[0] for x in prefix_tuples)

def common_suffix(strings):
    return common_prefix(map(reversed, strings))[::-1]

strings = ["aa1zz", "aaa2zzz", "aaaa3zzzz"]

assert common_prefix(strings) == "aa"
assert common_suffix(strings) == "zz"
© www.soinside.com 2019 - 2024. All rights reserved.