新聞中心
數(shù)字列表和其他列表類似,但是有一些函數(shù)可以使數(shù)字列表的操作更高效。我們創(chuàng)建一個(gè)包含10個(gè)數(shù)字的列表,看看能做哪些工作吧。

創(chuàng)新互聯(lián)成立于2013年,先為迎江等服務(wù)建站,迎江等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為迎江企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
# Print out the first ten numbers. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for number in numbers: print(number)
range() 函數(shù)
普通的列表創(chuàng)建方式創(chuàng)建10個(gè)數(shù)是可以的,但是如果想創(chuàng)建大量的數(shù)字,這種方法就不合適了。range() 函數(shù)就是幫助我們生成大量數(shù)字的。如下所示:
# print the first ten number for number in range(1, 11): print(number)
range() 函數(shù)的參數(shù)中包含開(kāi)始數(shù)字和結(jié)束數(shù)字。得到的數(shù)字列表中包含開(kāi)始數(shù)字但不包含結(jié)束數(shù)字。同時(shí)你也可以添加一個(gè) step 參數(shù),告訴 range() 函數(shù)取數(shù)的間隔是多大。如下所示:
# Print the first ten odd numbers. for number in range(1,21,2): print(number)
如果你想讓 range() 函數(shù)獲得的數(shù)字轉(zhuǎn)換為列表,可以使用 list() 函數(shù)轉(zhuǎn)換。如下所示:
# create a list of the first ten numbers. numbers = list(range(1,11)) print(numbers)
這個(gè)方法是相當(dāng)強(qiáng)大的?,F(xiàn)在我們可以創(chuàng)建一個(gè)包含前一百萬(wàn)個(gè)數(shù)字的列表,就跟創(chuàng)建前10個(gè)數(shù)字的列表一樣簡(jiǎn)單。如下所示:
# 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() 函數(shù)
如標(biāo)題所示,你可以將這三個(gè)函數(shù)用到數(shù)字列表中。min() 函數(shù)求列表中的最小值,max() 函數(shù)求值,sum() 函數(shù)計(jì)算列表中所有數(shù)字之和。如下所示:
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.") 分享文章:創(chuàng)新互聯(lián)Python教程:python中數(shù)字列表的詳細(xì)介紹
當(dāng)前鏈接:http://fisionsoft.com.cn/article/ccsgddh.html


咨詢
建站咨詢
