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

打印 python中的列表 可以通过以下方式实现:

null
  1. 使用 循环 : 从0遍历到len(list)并使用for循环逐个打印列表中的所有元素,这是执行此操作的标准做法。

    python

    # 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
    
  2. 不使用循环: *符号用于在一行中用空格打印列表元素。将所有元素打印成新行或按空格分隔 九月=”” sep=“,” 分别地

    python

    # 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 = "" )

    
    

    输出:

    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
    
  3. 将列表转换为字符串以显示: 如果是字符串列表,我们可以使用 加入 函数,但如果列表包含整数,则将其转换为字符串,然后使用 join()函数 将它们连接到字符串并打印字符串。

    python

    # 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
    
  4. 使用地图: 使用 地图() 如果列表不是字符串,则将列表中的每个项目转换为字符串,然后将其合并:

    python

    # 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 ( '' .join( map ( str , a)))

    
    

    输出:

    1 2 3 4 5
    in new line
    1
    2
    3
    4
    5
    
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享