在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
方法三:使用类方法以垂直方式打印列表的Python程序
定义了一个类来获取用户输入的字符串,并以垂直结构的形式打印出来。为了实现这个目标,使用了每个参数定义一个函数。函数 1 的时间复杂度为 O(1),因为它只接受一个字符串作为参数,函数 2 的时间复杂度为 O(n)。
算法
- 步骤 1 - 定义了一个类,并在之后提供了两个带有一个参数的函数。
-
步骤 2 - 定义了一个函数 1,并设置了字符串数据类型。
-
步骤 3 - 使用循环遍历用户输入的字符串。
-
步骤 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模块并使用类定义。这些方法从简单到困难的难度级别做了解释。