歡迎您光臨本站 註冊首頁

如何理解python中數字列表

←手機掃碼閱讀     e36605 @ 2020-06-03 , reply:0

數字列表和其他列表類似,但是有一些函數可以使數字列表的操作更高效。我們創建一個包含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(" The 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.")


知識點補充:

range()函數

在python中可以使用range()函數來產生一系列數字

 for w in range(1,11): print(w)


輸出:

 1 2 3 4 5 6 7 8 9 10 #注意:這裡的到10就結束了,不包括11

[e36605 ] 如何理解python中數字列表已經有240次圍觀

http://coctec.com/docs/python/shhow-post-236811.html