Python 列表练习 示例1 Python程序,找到给定列表中独特的数字。 L1 = [1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2] L2 = [] for x in L1: if x not in L2: L2.append(x) print (L2) PythonCopy 它将产生以下输出。 [1, 9, 6, 3, 4, 5, 2, 7, 8] PythonCopy 示例2 Python程序用于找出列表中所有数字的总和。 L1 = [1, 9, 1, 6, 3, 4] ttl = 0 for x in L1: ttl+=x print ("Sum of all numbers Using loop:", ttl) ttl = sum(L1) print ("Sum of all numbers sum() function:", ttl) PythonCopy 它将产生以下 输出− Sum of all numbers Using loop: 24 Sum of all numbers sum() function: 24 PythonCopy 示例3 Python程序创建一个包含5个随机整数的列表。 import random L1 = [] for i in range(5): x = random.randint(0, 100) L1.append(x) print (L1) PythonCopy 它将产生以下 输出 − [77, 3, 20, 91, 85] PythonCopy