當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python list()用法及代碼示例

在本教程中,我們將借助示例了解 Python list() 構造函數。

list() 構造函數在 Python 中返回一個列表。

示例

text = 'Python'

# convert string to list
text_list = list(text)
print(text_list)

# check type of text_list
print(type(text_list))

# Output: ['P', 'y', 't', 'h', 'o', 'n']
#         <class 'list'>

list() 語法

用法:

list([iterable])

參數:

list() 構造函數接受一個參數:

  • 可迭代(可選)- 一個可以是序列的對象(string,元組) 或集合 (,字典) 或任何迭代器對象

返回:

list() 構造函數返回一個列表。

  • 如果沒有傳遞參數,則返回一個空列表
  • 如果 iterable 作為參數傳遞,它會創建一個包含 iterable 項的列表。

示例 1:從字符串、元組和列表創建列表

# empty list
print(list())

# vowel string
vowel_string = 'aeiou'
print(list(vowel_string))

# vowel tuple
vowel_tuple = ('a', 'e', 'i', 'o', 'u')
print(list(vowel_tuple))

# vowel list
vowel_list = ['a', 'e', 'i', 'o', 'u']
print(list(vowel_list))

輸出

[]
['a', 'e', 'i', 'o', 'u']
['a', 'e', 'i', 'o', 'u']
['a', 'e', 'i', 'o', 'u']

示例 2:從集合和字典創建列表

# vowel set
vowel_set = {'a', 'e', 'i', 'o', 'u'}
print(list(vowel_set))

# vowel dictionary
vowel_dictionary = {'a': 1, 'e': 2, 'i': 3, 'o':4, 'u':5}
print(list(vowel_dictionary))

輸出

['a', 'o', 'u', 'e', 'i']
['o', 'e', 'a', 'u', 'i']

注意:在字典的情況下,字典的鍵將是列表的項目。此外,元素的順序將是隨機的。

示例 3:從迭代器對象創建列表

# objects of this class are iterators
class PowTwo:
    def __init__(self, max):
        self.max = max
    
    def __iter__(self):
        self.num = 0
        return self
        
    def __next__(self):
        if(self.num >= self.max):
            raise StopIteration
        result = 2 ** self.num
        self.num += 1
        return result

pow_two = PowTwo(5)
pow_two_iter = iter(pow_two)

print(list(pow_two_iter))

輸出

[1, 2, 4, 8, 16]

相關用法


注:本文由純淨天空篩選整理自 Python list()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。