簡體   English   中英

什么是僅打印字符串的某些行的最pythonic方式?

[英]What is the most pythonic way of printing only certain lines of a string?

假設我有一個跨越多行的字符串(不是文件):

multiline_string = '''I met a traveller from an antique land
Who said: Two vast and trunkless legs of stone
Stand in the desert... near them, on the sand,
Half sunk, a shattered visage lies, whose frown,
And wrinkled lip, and sneer of cold command,
Tell that its sculptor well those passions read
Which yet survive, stamped on these lifeless things,
The hand that mocked them and the heart that fed;

And on the pedestal these words appear:
'My name is Ozymandias, king of kings;
Look on my works, ye Mighty, and despair!'
Nothing beside remains. Round the decay
Of that colossal wreck, boundless and bare
The lone and level sands stretch far away.'''

我想只得到字符串的某些行,作為單個字符串(而不是字符串列表)。 一種方法是:

pedestal_lines = "\n".join(multiline_string.splitlines()[9:12])
print(pedestal_lines)

輸出:

And on the pedestal these words appear:
'My name is Ozymandias, king of kings;
Look on my works, ye Mighty, and despair!'

但是這種方式不是很好:它必須將字符串拆分為字符串列表,索引此列表,然后將列表與str.join()方法一起加入。 更不用說,它看起來很難看,而且不太可讀。 是否有更優雅/ pythonic的方式實現這一目標?

如果你不想分割字符串,你可以做到以下幾點:

  • 使用正則表達式在8行之后捕獲3行
  • 計算換行符的位置,並使用正確的位置將字符串切片一次

您將原諒我在下面的代碼中可能做過的一次性錯誤。

正則表達式

import re

print(re.sub("^(.*\n){8}((?:.*\n){3})(.*\n){1,}",r"\2",multiline_string))

(創建一組8行,然后一組3行,然后其余的,由第二組替換)

位置提取+切片

linefeed_pos = [i for i,c in enumerate(multiline_string) if c=="\n"]
print(multiline_string[linefeed_pos[7]:linefeed_pos[11]])

(在原始字符串中使用列表解析提取換行符的位置,然后使用這些行索引位置進行切片)。 這種方法的缺點是它計算所有索引,不僅直到上限綁定。 這可以通過將生成器理解包含在列表解析中來直接解決,以便在不再需要索引時停止:

linefeed_pos = [next (i for i,c in enumerate(multiline_string) if c=="\n") for _ in range(12)]

也許一個切片/提取比分離和加入性能更好(我明白看到一個大的列表只是為了選擇3行而浪費)是無法忍受的,但我不會稱之為pythonic。

如果性能/內存很重要,如果你有很多行,那么上面介紹的兩種方法都應該比你的更快。 如果沒有,那么堅持你的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM