用Python打印列表(4种不同方式)

2021年4月13日09:45:42 发表评论 2,007 次浏览

打印一个在python中列出可以通过以下方式完成:

使用for循环:

从0遍历到len(list)并使用for循环一张一张地打印列表的所有元素, 这是这样做的标准做法。

# Python program to print list
# using for loop
a = [ 1 , 2 , 3 , 4 , 5 ]
  
# printing the list using loop
for x in range ( len (a)):
     print a[x],

输出如下:

1 2 3 4 5

不使用循环:

*符号用于以单行带空格的方式打印列表元素。要以新行或空格分隔打印所有元素,请分别使用sep= " \n "或sep= ", "。

# Python program to print list
# without using loop
  
a = [ 1 , 2 , 3 , 4 , 5 ]
  
# printing the list using * operator separated 
# by space 
print ( * a)
  
# printing the list using * and sep operator
print ( "printing lists separated by commas" )
  
print ( * a, sep = ", " ) 
  
# print in new line
print ( "printing lists in new line" )
  
print ( * a, sep = "\n" )

输出如下:

1 2 3 4 5
printing lists separated by commas
1, 2, 3, 4, 5
printing lists in new line
1
2
3
4
5

将列表转换为字符串以便显示:如果是字符串列表,我们可以使用join()函数简单地将它们连接起来,但如果列表包含整数,则将其转换为字符串,然后使用join()函数将它们连接到字符串并打印字符串。

# Python program to print list
# by Converting a list to a 
# string for display
a = [ "Geeks" , "for" , "Geeks" ]
  
# print the list using join function()
print ( ' ' .join(a))
  
# print the list by converting a list of 
# integers to string 
a = [ 1 , 2 , 3 , 4 , 5 ]
  
print str (a)[ 1 : - 1 ]

输出如下:

Geeks for Geeks
1, 2, 3, 4, 5

使用map:如果list不是字符串,则使用map()将列表中的每一项转换为字符串,然后连接它们:

# Python program to print list
# print the list by converting a list of 
# integers to string using map
  
a = [ 1 , 2 , 3 , 4 , 5 ]
print ( ' ' .join( map ( str , a))) 
  
print "in new line"
print ( '\n' .join( map ( str , a)))

输出如下:

1 2 3 4 5
in new line
1
2
3
4
5

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: