在 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+ 次浏览

启动您的 职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.