Python list()

list() 构造函数将可迭代对象(字典、元组、字符串等)转换为 列表 并返回。

示例

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() 的语法是

list([iterable])

list() 参数

list() 构造函数接受一个参数


list() 返回值

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_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]

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战