python if / else list comprehension

时间:2018-01-16 15:48:29

标签: python

我想知道在下列情况下是否可以使用列表推导,或者它是否应该保留为for循环。

temp = []
for value in my_dataframe[my_col]:
  match = my_regex.search(value)
  if match:
    temp.append(value.replace(match.group(1),'')
  else:
    temp.append(value)

我相信我可以使用if / else部分,但是匹配'线让我失望。这很接近但不完全是。

temp = [value.replace(match.group(1),'') if (match) else value for 
    value in my_dataframe[my_col] if my_regex.search(value)]

3 个答案:

答案 0 :(得分:2)

单一陈述方法:

result = [
    value.replace(match.group(1), '') if match else value
    for value, match in (
        (value, my_regex.search(value))
        for value in my_dataframe[my_col])]

功能方法 - python 2:

data = my_dataframe[my_col]
gen = zip(data, map(my_regex.search, data))
fix = lambda (v, m): v.replace(m.group(1), '') if m else v
result = map(fix, gen)

功能方法 - python 3:

from itertools import starmap
data = my_dataframe[my_col]
gen = zip(data, map(my_regex.search, data))
fix = lambda v, m: v.replace(m.group(1), '') if m else v
result = list(starmap(fix, gen))

务实的方法:

def fix_string(value):
    match = my_regex.search(value)
    return value.replace(match.group(1), '') if match else value

result = [fix_string(value) for value in my_dataframe[my_col]]

答案 1 :(得分:0)

这实际上是列表推导的一个很好的例子,它比相应的for-loop表现更差,并且(远)可读性更低。

如果你想这样做,那就是这样:

temp = [value.replace(my_regex.search(value).group(1),'') if my_regex.search(value) else value for value in my_dataframe[my_col]]
#                              ^                                      ^

请注意,我们无法在理解中定义match,因此我们必须两次调用my_regex.search(value)。这当然效率低下。

因此,坚持使用for循环!

答案 2 :(得分:0)

使用带有子组模式的正则表达式模式查找任何单词,直到找到空格加字符和字符 he 加字符,并找到空格加字符和 el 加任何字符。重复子组模式

paragraph="""either the well was very deep, or she fell very slowly, for she had
plenty of time as she went down to look about her and to wonder what was
going to happen next. first, she tried to look down and make out what
she was coming to, but it was too dark to see anything; then she
looked at the sides of the well, and noticed that they were filled with
cupboards and book-shelves; here and there she saw maps and pictures
hung upon pegs. she took down a jar from one of the shelves as
she passed; it was labelled 'orange marmalade', but to her great
disappointment it was empty: she did not like to drop the jar for fear
of killing somebody, so managed to put it into one of the cupboards as
she fell past it."""

sentences=paragraph.split(".")

pattern="\w+\s+((\whe)\s+(\w+el\w+)){1}\s+\w+"
temp=[]
for sentence in sentences:
    result=re.findall(pattern,sentence)
    for item in result:
        temp.append("".join(item[0]).replace(' ',''))
print(temp)               

输出:

['thewell', 'shefell', 'theshelves', 'shefell']