Skip to main content
 首页 » 编程设计

python之str.strip 是否功能失调

2025年05月04日13qq78292959

我有一个从字符串拆分操作构建的列表,我想将它输入到 map() 函数,然后从它们的尾随括号和空格中删除这些子字符串。 并从中重建一个列表。

teststring=" (A) / (B) " 
result = list(map(str.strip, teststring.split("/"), " ()")) 

但最后,我只奇怪地剥 ionic 字符串,而“所有组合都经过测试”,如文档所述。

我知道另一种方法可用于列表理解:

result = [substr.strip(' ()' for substr in teststring.split("/")]   

哪个有效.. 但我想知道为什么 map 不能正常工作。

我在 python 3.6.4 上,在 windows64 上使用 Anaconda 4.4。

附属问题;以下topic给出了一些查找函数源代码的指针。但是我找不到 map 的代码(通常是内置函数的代码),所以我看不出它是否有错误...

请您参考如下方法:

带有 3 个参数的

map 的行为方式与您想象的不同。 map 的第三个参数不是作为第一个参数提供的函数的参数。它用作第二个可迭代对象。

来自docs :

map(function, iterable, ...) Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap()

换句话说:

map(str.strip, teststring.split('/'), '()') 不等同于

[substr.strip(' ()' for substr in teststring.split('/')]。它远等同于

[(substr_1.strip(), substr_2.strip()) for (substr_1, substr_2) in zip(teststring.split("/"), ' ()')]

看出区别了吗?