数字列表和其他列表类似,但是有一些函数可以使数字列表的操作更高效。我们创建一个包含10个数字的列表,看看能做哪些工作吧。
# Print out the first ten numbers.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers:
print(number)
range() 函数
普通的列表创建方式创建10个数是可以的,但是如果想创建大量的数字,这种方法就不合适了。range() 函数就是帮助我们生成大量数字的。如下所示:
# print the first ten number
for number in range(1, 11):
print(number)
range()函数的参数中包含开始数字和结束数字。得到的数字列表中包含开始数字但不包含结束数字。同时你也可以添加一个step参数,告诉range()函数取数的间隔是多大。如下所示:
# Print the first ten odd numbers.
for number in range(1,21,2):
print(number)
如果你想让range()函数获得的数字转换为列表,可以使用list()函数转换。如下所示:
# create a list of the first ten numbers.
numbers = list(range(1,11))
print(numbers)
这个方法是相当强大的。现在我们可以创建一个包含前一百万个数字的列表,就跟创建前10个数字的列表一样简单。如下所示:
# Store the first million numbers in a list
numbers = list(range(1,1000001))
# Show the length of the list
print("The list 'numbers' has " + str(len(numbers)) + " numbers in it.")
# Show the last ten numbers.
print("\nThe last ten numbers in the list are:")
for number in numbers[-10:]:
print(number)
min(), max() 和 sum() 函数
如标题所示,你可以将这三个函数用到数字列表中。min() 函数求列表中的最小值,max() 函数求最大值,sum() 函数计算列表中所有数字之和。如下所示:
ages = [23, 16, 14, 28, 19, 11, 38]
youngest = min(ages)
oldest = max(ages)
total_years = sum(ages)
print("Our youngest reader is " + str(youngest) + " years old.")
print("Our oldest reader is " + str(oldest) + " years old.")
print("Together, we have " + str(total_years) +
" years worth of life experience.")
动手试一试
First Twenty
使用 range() 函数在列表中存储前20个数字(1-20),并且打印出来。
Five Wallets
想象5个钱包,每个钱包里有不同数量的不同数字的现金,把5个钱包和其中的现金用列表表示出来。
打印出现金最多的钱包的现金数。
打印出现金最少的钱包的现金数。
打印所有的现金数。
# Ex : Five Wallets
#Imagine five wallets with different amounts of cash in them. Store these five values in a list,
#and print out the following sentences:
#"The fattest wallet has ∗value∗init."−"Theskinniestwallethas value in it."
#"All together, these wallets have $ value in them."
from random import randint
wallets = [ [randint(1,100) for _ in range(randint(2,10))] for _ in range(5) ]
print(wallets)
amounts = [ sum(wallet) for wallet in wallets ]
print(amounts)
print('The fattest wallet has {} in it'.format(max(amounts)))
print('All together, these wallets have {} value in them'.format(sum(amounts)))
print('The thinnest wallet has {} in it'.format(min(amounts)))
网友评论