簡體   English   中英

從字符串操作列表中的項目,然后將其轉回字符串

[英]Manipulating items in a list, from a string then turning it back to a string

不久前我申請了一份數據工程師的工作,我收到了一個 Python 問題,它沒有滿足所有的邊緣情況,從那以后它一直困擾着我,我當時使用.endswith() ,我覺得這就是失敗的原因在我的代碼中

我一直在嘗試重新編碼它,這是我到目前為止所擁有的:

x = 'cars that ran up and opened a 
tattooaged car dealership educated'
# create a program to remove 'ed' from 
# any word that ends with ed but not 
# the word 'opened'
# also, every word must be less than 
# 8 letters long

suffix= 'ed'

def check_ed_lt8(x):
    x_list=x.split(" ")
    for index,var in enumerate(x_list):
        if suffix in var != 'opened':
            new_word = var[:-len(suffix)].strip('suffix')
            x_list[index] = new_word
        elif len(var) >= 8:
            shorter_word = var[:8]
            x_list[index] = shorter_word
    return(' '.join(x_list))

print(check_ed_lt8(x))

我得到了想要的 output:

cars that ran up and opened a tatooag car dealersh educat

但是技術問題之前有一些例子,比如一些以“ly”結尾的單詞,我開始想知道我是否可能只需要遍歷一個后綴列表,這就是為什么我沒有通過邊緣情況,所以我修改了我的代碼但是現在,每次我添加到列表中時,我都會失去對列表中最后一項的操作

suffixes = ['ed', 'an']
def check_ed_lt8(x):
    x_list=x.split(" ")
    for index,var in enumerate(x_list):
        for suffix in suffixes:
            if suffix in var != 'opened':
                new_word = var[:-len(suffix)].strip('suffix')
                x_list[index] = new_word
            elif len(var) >= 8:
                shorter_word = var[:8]
                x_list[index] = shorter_word
    return(' '.join(x_list))

print(check_ed_lt8(x))

回報:

cars that r up a opened a tattoag car dealersh educated

在這次回歸中,我失去了對最后一項的操縱,我並不是說“and”會失去“nd”。 我知道它因為每個前綴中的“d”和“n”的組合而丟失了,但我不知道為什么

我在前綴中放置的項目越多,對最后幾項的操作就越多,例如,如果我在前綴中添加“ars”,結果將變為:

c that r up a opened a tattoag car dealership educated 

我究竟做錯了什么?

我建議在最后使用 re.sub 刪除 ed 。 這是一個單行:

import re
x = 'cars that ran up and opened a tattoo aged car dealership educated'
y = ' '.join([w if w == "opened" else re.sub(r'ed$', '', w)[:8] for w in x.split(' ')])

如果要刪除多個后綴,請相應地擴展您的正則表達式:

y = ' '.join([w if w == "opened" else re.sub(r'(ed|an)$', '', w)[:8] for w in x.split(' ')])

當然,您也可以根據后綴列表構建正則表達式:

suffixes = ['ed','an']
pattern = re.compile('('+'|'.join(suffixes)+')$')
y = ' '.join([w if w == "opened" else pattern.sub('', w)[:8] for w in x.split(' ')])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM