【发布时间】:2020-06-20 05:24:44
【问题描述】:
我有一个“句子”列表(有 3000 个字符串),如下所示:
sentences[0:5]
['So there is no way for me to plug it in here in the US unless I go by a converter.',
'Good case, Excellent value.',
'Great for the jawbone.',
'Tied to charger for conversations lasting more than 45 minutes.MAJOR PROBLEMS!!',
'The mic is great.']
我想从这个列表中的每个字符串中删除数字。例如上例中第 4 个字符串中的“45”。
当我使用嵌套循环时,它不会给出想要的结果。相反,它重复每个字符串句子等于“数字”列表中的位数,如下所示:
digits=[str(i) for i in range(0,10)]
t=[]
for i in sentences:
for j in digits:
a=i.replace(j,'')
t.append(a)
print(t[0:5])
['So there is no way for me to plug it in here in the US unless I go by a converter.', 'So there is no way for me to plug it in here in the US unless I go by a converter.', 'So there is no way for me to plug it in here in the US unless I go by a converter.', 'So there is no way for me to plug it in here in the US unless I go by a converter.', 'So there is no way for me to plug it in here in the US unless I go by a converter.']
但是,当我创建一个函数然后在列表理解中调用它时,它可以完美地工作,如下所示:
def full_remove(x,remove_list):
for i in remove_list:
x=x.replace(i,' ')
return x
digits=[str(x) for x in range(10)]
digit_less=[full_remove(i,digits) for i in sentences]
print(digit_less[0:5])
['So there is no way for me to plug it in here in the US unless I go by a converter.', 'Good case, Excellent value.', 'Great for the jawbone.', 'Tied to charger for conversations lasting more than minutes.MAJOR PROBLEMS!!', 'The mic is great.']
据我了解,这里在列表理解中调用函数的逻辑与使用嵌套循环相同,但是为什么嵌套循环不起作用?我在哪里犯错了?
请解释一下。
谢谢
【问题讨论】:
-
仔细想想:对于原始列表中的每一个句子,输出列表中应该附加多少修改后的句子?现在,您在第一种情况下实际发生了多少次?你能想出一个理由吗?仔细考虑执行附加的代码部分。它会被调用多少次?如果您从
sentences的较短版本开始,您将获得更清晰的画面,但显示整个输出(而不是切片)以进行调试。 -
(但是一旦你修复它,请坚持使用理解的版本。这是组织代码的更好方法;你将修复句子的责任与迭代输入。)
-
感谢卡尔的回复。我已经检查过,当迭代器到达字符串具有的那个数字时,它确实删除了字符串中的数字。但随后它继续附加字符串,直到“数字”列表中的所有数字都被迭代。我在“数字”列表中有 10 位数字(从 0 到 9),所以它迭代并附加每个字符串 10 次。
-
是的;现在,你能想出为什么它一直附加该字符串 10 次的原因吗?提示:
digits列表中有多少位数字? -
是的,现在为什么要为每个数字附加一个单独的时间?提示:代码中的
append调用在哪里,它是如何缩进的?我问这些问题是因为如果您希望学习 Python(或任何其他编程语言),您需要能够通过仔细分析情况自己解决问题。
标签: python string list list-comprehension nested-loops