Python 列表方法 - in、not in、len()、min()、max()


在本文中,我們將學習 Python 3.x(或更早版本)中各種型別的列表方法。這些運算子允許我們對列表內容執行基本操作。

in 和 not in 運算子

  • “in” 運算子 − 此運算子用於檢查元素是否出現在指定的列表中。如果元素存在於列表中,則返回 true,否則返回 false。

  • “not in” 運算子 − 此運算子用於檢查元素是否不出現在指定的列表中。如果元素不存在於列表中,則返回 true,否則返回 false。讓我們來看一個例子來更好地理解它。

示例

lis = ['t','u','t','o','r','i','a','l']
# in operator
if 't' in lis:
   print ("List is having element with value t")
else :
   print ("List is not having element with value t")
# not in operator
if 'p' not in lis:
   print ("List is not having element with value p")
else :
   print ("List is having element with value p")

輸出

List is having element with value t
List is not having element with value p

len()、max() 和 min() 運算子

  • len() − 此函式返回列表的長度。如果物件與長度無關,則會引發錯誤。

  • min() − 此函式返回列表中的最小元素。

  • max() − 此函式返回列表中的最大元素。

讓我們來看一個例子來更好地理解它。

示例

lis = ['t','u','t','o','r','i','a','l']

# len()
print ("The length of list is : ", end="")
print (len(lis))

# min()
print ("The minimum element of list is : ", end="")
print (min(lis))

# max()
print ("The maximum element of list is : ", end="")
print (max(lis))

輸出

The length of list is : 8
The minimum element of list is : a
The maximum element of list is : u

結論

在本文中,我們學習瞭如何實現 in 和 not in 運算子以及 len()、max() 和 min() 方法。

更新於:2020年7月1日

22K+ 瀏覽量

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告