Python list()

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

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

列表()参数:

只接受一个参数。在这种情况下,序列可以是字符串,元组和集合可以是集合,字典。

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

列表()返回值

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

| 投入 | 返回值 | | 没有参数 | 空列表 | | 可迭代通过 | 由可重复项目组成的列表 |

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] 

本文链接:https://my.lmcjl.com/post/6334.html

展开阅读全文

4 评论

留下您的评论.