从字符串操作列表中的项目,然后将其转回字符串

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

提问人:Jrtm96 提问时间:9/7/2022 最后编辑:tobias_kJrtm96 更新时间:9/7/2022 访问量:50

问:

不久前,我申请了一份数据工程师的工作,我遇到了一个不符合所有边缘情况的 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))

我得到所需的输出:

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 

我做错了什么?

python 字符串 列表 数据操作 后缀

评论

0赞 mkrieger1 9/7/2022
第一个例子在句法上似乎没有意义。请注意混乱的语法突出显示。
0赞 Jrtm96 9/7/2022
我修复了我能修复的,如何在这里多行评论?是html吗?
0赞 tobias_k 9/7/2022
if suffix in var != 'opened':这应该做什么?看起来这实际上是有效的比较链接,但请不要这样做。
0赞 Jrtm96 9/7/2022
@tobias_k好的,我会接受你的建议并研究它,谢谢!
0赞 Community 9/8/2022
请澄清您的具体问题或提供其他详细信息,以准确说明您的需求。正如目前所写的那样,很难确切地说出你在问什么。

答:

0赞 treuss 9/7/2022 #1

我建议使用 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(' ')])

评论

0赞 Jrtm96 9/7/2022
老实说,我需要更多地接触 regx,感谢您的反馈!我今天晚些时候会尝试一下!
0赞 Jrtm96 9/8/2022
哇!这就像一个魅力!我有很多东西要学,再次感谢!