我正试图写一个代码来删除所有的单词从一组单词之后的某个单词,如下所示。我测试了一下,但由于我对python很陌生,我不确定这段代码是否会导致问题。
是否有人可以检查这些代码并指出使用这些代码可能存在的风险?
def to_lowercase(target):
lowerlist=[x.lower() for x in target];
for i in range(len(target)):
target[i]=lowerlist[i]
def remove_equipment(targetlist):
wordtarget=''
for x in targetlist:
if x in targetword:
index =targetlist.index(x)
del targetlist[index:]
targetword=['equipment:','accompaniments:','garnish:']
to_lowercase(testlist);
remove_equipment(testlist);
我用下面的测试列表进行了测试。
testlist= ['brioche','sandwich','bread,','shrimp,','peeled,','tail','fan','attached,','butter','dill','shallot','Equipment:','cups']
到目前为止,我还没有看到任何错误。
这可能有效,但一些建议:
- 将预期结果存储在单独的列表中,而不是更改(突变)原始
testlist
。如果您需要比较更改前后的列表,这将非常有用。 - 约定是使用下划线来分隔变量名中的单词:
test_list
而不是testlist
- 避免通过
test_list
多次循环。目前,to_lowercase
循环一次,remove_equipment
循环一次,targetlist.index(x)
也将循环一次。请看下面的简化方法:
test_list = ['brioche','sandwich', 'bread,','shrimp,','peeled,','tail','fan','attached,','butter','dill','shallot','Equipment:','cups']
target_word = ['equipment:','accompaniments:','garnish:']
# to store results
res = []
for word in test_list:
# assumes you want only lowercase results
word = word.lower()
# add word to result list.
# assumes that you want to keep words up to and including the target word.
# e.g. [..., 'garnish:']
res.append(word)
if word in target_word:
# break to end the for-loop since you don't want anything beyond this word
break
print(res)
# prints ['brioche', 'sandwich', 'bread,', 'shrimp,', 'peeled,', 'tail', 'fan', 'attached,', 'butter', 'dill', 'shallot', 'equipment:']
我觉得你的实现很好,还可以简化一下。
def to_lowercase(target):
return [x.lower() for x in target]
def remove_equipment(targetlist):
last_index = len(targetlist)
for i, x in enumerate(targetlist):
if x in targetword:
last_index = i + 1
break
return targetlist[:last_index]
testlist= ['brioche','sandwich','bread,','shrimp,','peeled,','tail','fan','attached,','butter','dill','shallot','Equipment:','cups']
targetword = ['equipment:','accompaniments:','garnish:']
testlist = to_lowercase(testlist)
testlist = remove_equipment(testlist)
print(testlist)
##output
['brioche', 'sandwich', 'bread,', 'shrimp,', 'peeled,', 'tail', 'fan', 'attached,', 'butter', 'dill', 'shallot', 'equipment:']
一旦条件满足,请记住中断循环。
您可以使用:
targetword=['equipment:','accompaniments:','garnish:']
testlist= [i.lower() for i in ['brioche','sandwich','bread,','shrimp,','peeled,','tail','fan','attached,','butter','dill','shallot','Equipment:','cups']]
for w in targetword:
if w in testlist:
try:
del testlist[testlist.index(w) + 1]
except:
print("Index out of bounds")
print(testlist)
# ['brioche', 'sandwich', 'bread,', 'shrimp,', 'peeled,', 'tail', 'fan', 'attached,', 'butter', 'dill', 'shallot', 'Equipment:']
演示