列表理解..我疯了吗?
List Comprehension.. am I crazy?
我有一个 phone 个号码的列表
phone_numbers = [000-000-0000, 000-000-0000, 000-000-0000]
for number in phone_numbers:
x = list(filter(str.isdigit, number.strip()))
t = "".join(x)
给我想要的结果 0000000000
是否可以为此目的使用列表推导式,还是我完全不用了?
[list(filter(str.isdigit, x.strip())) for x in phone_numbers]
是的,您可以使用列表理解。
["".join(filter(str.isdigit, number.strip())) for number in phone_numbers]
这里有一些解决方案,
import re
phone_numbers = ["000-000-0000", "000-000-0000", "000-000-0000"]
>>> ["".join(re.findall("\d+", p)) for p in phone_numbers]
['0000000000', '0000000000', '0000000000']
或
>>> ["".join(x for x in p if x.isdigit()) for p in phone_numbers]
['0000000000', '0000000000', '0000000000']
我有一个 phone 个号码的列表
phone_numbers = [000-000-0000, 000-000-0000, 000-000-0000]
for number in phone_numbers:
x = list(filter(str.isdigit, number.strip()))
t = "".join(x)
给我想要的结果 0000000000
是否可以为此目的使用列表推导式,还是我完全不用了?
[list(filter(str.isdigit, x.strip())) for x in phone_numbers]
是的,您可以使用列表理解。
["".join(filter(str.isdigit, number.strip())) for number in phone_numbers]
这里有一些解决方案,
import re
phone_numbers = ["000-000-0000", "000-000-0000", "000-000-0000"]
>>> ["".join(re.findall("\d+", p)) for p in phone_numbers]
['0000000000', '0000000000', '0000000000']
或
>>> ["".join(x for x in p if x.isdigit()) for p in phone_numbers]
['0000000000', '0000000000', '0000000000']