Takewhile lambda 函数无法识别字符串
Takewhile lambda function not recognizing string
所以我在文件的开头有一个评论部分。我想要的是要拉出以“# Description:”开头的行。但由于某种原因我不明白,它不起作用。
输入“#”得到我所期望的结果,“# NOTE”也是如此,但是“# Description:”甚至“# D”似乎 return 什么都没有。有人可以帮我理解吗?
这是我文件的评论部分:
# NOTE: successive whitespace characters treated as single delimiter
# NOTE: all lines beginning with '#' treated as comments
# NOTE: Description must come after '# Description: ' to be recognized
#
# Description: High dispersion optics with O-16 (4+) at 6 MeV/nucleon. Provided by <first, last> on <datetime>.
#
#
这是我使用的代码:
from itertools import takewhile
with open(pathname, 'r') as fobj:
# takewhile returns an iterator over all the lines
# that start with the comment string
headiter = takewhile(lambda s: s.startswith('# Description: '), fobj)
description = list(headiter)
takewhile
将 保留 迭代器中的元素,直到条件为 False。在您的情况下,条件在开始时为 False,仅在第三行变为 True。
您想使用 dropwhile
和 next
:
from itertools import dropwhile
with open(pathname, 'r') as fobj:
# dropping lines until they don't start with "# Description:"
headiter = dropwhile(lambda s: not s.startswith('# Description: '), fobj)
# getting next element
description = next(headiter)
输出:
'# Description: High dispersion optics with O-16 (4+) at 6 MeV/nucleon. Provided by <first, last> on <datetime>.'
所以我在文件的开头有一个评论部分。我想要的是要拉出以“# Description:”开头的行。但由于某种原因我不明白,它不起作用。 输入“#”得到我所期望的结果,“# NOTE”也是如此,但是“# Description:”甚至“# D”似乎 return 什么都没有。有人可以帮我理解吗?
这是我文件的评论部分:
# NOTE: successive whitespace characters treated as single delimiter
# NOTE: all lines beginning with '#' treated as comments
# NOTE: Description must come after '# Description: ' to be recognized
#
# Description: High dispersion optics with O-16 (4+) at 6 MeV/nucleon. Provided by <first, last> on <datetime>.
#
#
这是我使用的代码:
from itertools import takewhile
with open(pathname, 'r') as fobj:
# takewhile returns an iterator over all the lines
# that start with the comment string
headiter = takewhile(lambda s: s.startswith('# Description: '), fobj)
description = list(headiter)
takewhile
将 保留 迭代器中的元素,直到条件为 False。在您的情况下,条件在开始时为 False,仅在第三行变为 True。
您想使用 dropwhile
和 next
:
from itertools import dropwhile
with open(pathname, 'r') as fobj:
# dropping lines until they don't start with "# Description:"
headiter = dropwhile(lambda s: not s.startswith('# Description: '), fobj)
# getting next element
description = next(headiter)
输出:
'# Description: High dispersion optics with O-16 (4+) at 6 MeV/nucleon. Provided by <first, last> on <datetime>.'