在Python中打印列表(4 种不同的方式)
在Python中打印列表可以通过以下方式完成:
- 使用 for 循环:从 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],
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 = "\n")
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]
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('\n'.join(map(str, a)))
输出:1 2 3 4 5
- 不使用循环: * 符号用于将列表元素打印在带有空格的单行中。要在新行中打印所有元素或用空格分隔,请分别使用sep=”\n”或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 = "\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
# 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
# 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