在 Python 中垂直列印列表


Python 語言由各種資料結構組成,其中最常見的是列表資料結構。列表可以包含整數或字串元素(用單引號或雙引號括起來),並用方括號括起來。執行程式時,輸出以標準格式列印,但這篇文章討論的是如何將輸出以垂直形式作為單獨的列表返回。列表資料結構中的元素可以透過索引值識別。

垂直列印列表

列表中的元素按某種順序排列,資料分配後無法更改。下面給出了帶有元素的列表的基本結構:

語法

list1 = [1, 3, “Hello”, “yes”] 

當上述語句列印時,它將以水平格式顯示。

方法

方法 1 - 使用巢狀 for 迴圈

方法 2 - 使用 itertools 模組

方法 3 - 使用類方法

方法 1:使用巢狀 for 迴圈以垂直方式列印列表的 Python 程式

巢狀 for 迴圈用於以垂直結構提供輸入。以下程式碼的時間複雜度為 O(n^2),因為它使用了兩個巢狀 for 迴圈。外迴圈遍歷子列表,每個專案都由內迴圈迭代。迭代次數等於給定列表長度的平方。

演算法

  • 步驟 1 - 定義包含整數和字串值的列表輸入。

  • 步驟 2 - 使用 for 迴圈遍歷列表,並再次使用巢狀 for 迴圈進行迭代。

  • 步驟 3 - 根據輸入列印輸出為垂直列表。

示例

#initializing the list along with the sublist of elements in the form of integer and string
list1 = [[20, 40, 50], [79, 80], ["Hello"]]
#for loop is used to iterate through the list of elements 
for listmethod in list1:
	#nested for loop to iterate through the list using the item
	for item in listmethod:
    #print statement will return the item in terms of a list
	   print("[", item, "] ")

輸出

[20]
[40]
[50]
[79]
[80]
[Hello]

方法 2:使用 itertools 庫以垂直方式列印列表的 Python 程式

使用 itertools 模組,即使對於複雜的運算,迭代過程也更容易。從此模組中,使用 zip_longest 函式以垂直方式列印列表。上述程式碼的時間複雜度為 O(n)。迭代過程結束後,使用 join 函式對單獨的列表進行分組。

演算法

  • 步驟 1 - 在列表中定義包含某些整數元素的輸入。

  • 步驟 2 - 匯入 itertools 庫,使迭代過程更容易。

  • 步驟 3 - 利用 zip_longest 函式遍歷列表,以填充空白。

  • 步驟 4 - 然後檢查給定列表中是否有任何帶空格的元素。

  • 步驟 5 - 基於空格,如果給出空格,則按原樣返回元素;如果沒有空格,則插入空格。

示例

#initializing the list of elements
list1 = [[20, 40, 50], [79, 80], ["Hello"]]
#importing the module
import itertools
#for loop used for iteration 
#zip_longest function to deal with the spaces
for a in itertools.zip_longest(*list1, fillvalue= " "):
	if any(b != " " for b in a):
    #returns the final output in vertical structure
	   print(" ".join(str(b) for b in a))

輸出

20 79 Hello
40 80
50

方法 3:使用類方法以垂直方式列印列表的 Python 程式

定義類以獲取使用者提示的字串,並將字串以垂直結構的形式打印出來。為此,使用每個引數定義函式。function1 的時間複雜度為 O(1),因為它只接受一個字串;function2 的時間複雜度為 O(n)。

演算法

  • 步驟 1 - 定義類,然後提供兩個帶一個引數的函式。

  • 步驟 2 - 使用字串資料型別定義 function1。

  • 步驟 3 - 使用 for 迴圈遍歷使用者提供的字串。

  • 步驟 4 - 然後呼叫函式以獲取字串和字串的字元。

示例

#defining the class as string_ver
class string_ver:
#defining two functions as function1 and function2
	def function1(self):
 		self.list = ['20', '40', '50', '79', '80', "Hello"]
	def function2(self):
		for a in self.list:
			print("\t " + a)
string = string_ver()
string.function1()
string.function2()

輸出

    20
    40
    50
    79
    80
    Hello

結論

列表資料結構可以用數字、字串或浮點數初始化。使用巢狀迴圈、匯入 itertools 模組以及使用類定義,將定義的輸入以垂直形式對齊。從簡單方法到難度級別,解釋了各種方法。

更新於:2023年8月29日

5K+ 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始
廣告