Tutorial Study Image

Python list()

Python 中的 list() 函数有助于返回一个列表对象。Python 中的列表是有序的,并且具有精确的计数。列表组件是带索引的,因此索引从零开始。


list([iterable]) # object can be string,sets,tuples,dictionary etc

list() 参数

只接受一个参数。其中序列可以是字符串、元组,集合可以是集合、字典。

参数 描述 必需/可选
可迭代对象 一个可以是序列或集合的任何可迭代对象 可选

list() 返回值

它返回一个列表,并且只有一个参数。

输入 返回值
无参数 空列表
传入可迭代对象 包含可迭代对象项的列表

Python 中 list() 方法的示例

示例 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_dicti 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]