繁体   English   中英

python if/else列表理解

[英]python if/else list comprehension

我想知道在以下情况下是否可以使用列表理解,或者是否应该将其保留为 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)]

单语句方法:

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]]

这实际上是列表推导式的一个很好的例子,它的性能比其相应的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]]
#                              ^                                      ^

请注意,我们无法在my_regex.search(value)内部定义match ,因此我们必须两次调用my_regex.search(value) .. 这当然是低效的。

因此,坚持 for 循环!

使用带有子组模式的正则表达式模式查找任何单词,直到找到空格加字符和字符 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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM