我想要转换像以下这样的字符串:
' 1 , 2 , , , 3 '
转换为一个非空元素列表:
['1', '2', '3']
我的解决方案是这个列表推导式:
print [el.strip() for el in mystring.split(",") if el.strip()]
不知道是否有一种好的、符合Python风格的方法,可以在不调用el.strip()
两次的情况下编写这个推导式?
我想要转换像以下这样的字符串:
' 1 , 2 , , , 3 '
转换为一个非空元素列表:
['1', '2', '3']
我的解决方案是这个列表推导式:
print [el.strip() for el in mystring.split(",") if el.strip()]
不知道是否有一种好的、符合Python风格的方法,可以在不调用el.strip()
两次的情况下编写这个推导式?
您可以在列表推导式中使用生成器:
[<b>x for x in (el.strip()</b> for el in mylist.split(",")<b>)</b> if <b>x</b>]
# \__________________ ___________________/
# v
# internal generator
生成器会提供剥离后的元素,我们迭代生成器,并仅检查真实性。这样我们就可以节省掉el.strip()的调用。
您也可以使用map(..)来实现这一点(使其更加函数化):
生成器将提供剥离的元素, 我们迭代生成器, 并只检查真实性. 这样做可以节省对 el.strip()
的调用。
您还可以使用map(..)
来实现这一点(使其更具函数式风格):
[x for x in <b>map(str.strip,</b> mylist.split(",")<b>)</b> if x]
# \______________ ________________/
# v
# map
但基本上这是一样的(尽管生成器的逻辑在我看来更好地封装了)。
import re
s = ' 1 , 2 , , , 3 '
print(re.findall(r'[^\s,]+', s))
['1', '2', '3']
来试试使用正则表达式
从字符串中提取所有数字吧。
import re
a = ' 1 , 2 , , , 3 '
print(re.findall(r'\d+', a))
输出:
['1', '2', '3']
filter(lambda x: x, map(lambda x: x.strip(), mylist.split(',')))
但是这样做会以简洁为代价失去可见性。
map
有点过头了。你可以直接把 OP 的理解放进去,不需要 if
。 - Ma0filter(None,map(str.strip, mystring.split(",")))
会变得更加简洁。需要翻译的内容已完成。 - Chris_Rands通过使用map
和filter
,全面实现功能:
s = ' 1 , 2 , , , 3 '
res = filter(None, map(str.strip, s.split(',')))
x for x in iterable if x
,而map
将方法str.strip
(其默认分割值为空格)映射到从s.split(',')
获得的可迭代对象上。filter
仍然返回列表,因此这种方法的速度应该很快地超越其他方法。
res = [*filter(None, map(str.strip, s.split(',')))]
import re
s=' 1 , 2 , , , 3 '
print ([el for el in re.split(r"[, ]+",s) if el])
['1', '2', '3']
import re
s=' ,,,,, ,,,, 1 , 2 , , , 3,,,,,4 5, 6 '
print ([el for el in re.split(r"\s*,\s*",s.strip()) if el])
['1', '2', '3', '4 5', '6']
' a b, qux foo, 1 2 3'
。将导致 'a','b','qux','foo','1','2','3'
。 - Willem Van Onsemresult = []
for el in mystring.split(",")
x = el.strip()
if x:
result.append(x)
all_terms = [el.strip() for el in mystring.split(",")]
non_empty_terms = [x for x in all_terms if x]
其他答案中有些确实更短,但我并不认为它们更简单易懂。实际上,我认为最好的答案就是你问题中的那个,因为这种情况下的重复相当少。