首页 > 编程知识 正文

Python 程序:打印列表中元素

时间:2023-11-24 15:33:41 阅读:308906 作者:BATV

写一个 Python 程序,用一个实例打印列表中的元素。

打印列表元素的 Python 程序示例 1

Python 打印功能自动打印列表中的元素。

# Python Program to print Elements in a List 

a = [10, 50, 60, 80, 20, 15]

print("Element in this List are : ")
print(a)
Element in this List are : 
[10, 50, 60, 80, 20, 15]

返回列表元素的 Python 程序示例 2

这个 python 程序同上。但是这次,我们使用 For Loop 来迭代列表中的每个元素,并打印该元素。这种方法对于使用这个 Python 索引位置改变单个项目非常有用。

# Python Program to print Elements in a List 

a = [10, 50, 60, 80, 20, 15]

print("Element in this List are : ")
for i in range(len(a)):
    print("Element at Position %d = %d" %(i, a[i]))
Element in this List are : 
Element at Position 0 = 10
Element at Position 1 = 50
Element at Position 2 = 60
Element at Position 3 = 80
Element at Position 4 = 20
Element at Position 5 = 15

显示列表元素的 Python 程序示例 3

Python 打印函数还打印列表中的字符串元素。

# Python Program to print Elements in a List 

Fruits = ['Apple', 'Orange', 'Grape', 'Banana']

print("Element in this List are : ")
print(Fruits)

打印列表项输出

Element in this List are : 
['Apple', 'Orange', 'Grape', 'Banana']

返回列表元素的 Python 程序示例 4

这个 Python 列表项目程序和上面的一样。但是,我们使用 For 循环来迭代列表中的每个字符串元素。

# Python Program to print Elements in a List 

Fruits = ['Apple', 'Orange', 'Grape', 'Banana']

print("Element in this List are : ")
for fruit in Fruits:
    print(fruit)
Element in this List are : 
Apple
Orange
Grape
Banana

显示列表元素的 Python 程序示例 5

这个 Python 程序允许用户输入任意整数值,是一个 List 的长度。接下来,我们使用 For 循环向列表中添加数字。

# Python Program to print Elements in a List 

NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
    NumList.append(value)

for i in range(Number):
    print("The Element at index position %d = %d " %(i, NumList[i]))

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。