📅  最后修改于: 2020-09-20 13:38:50             🧑  作者: Mango
list()
的语法为:
list([iterable])
list()
构造函数采用一个参数:
list()
构造函数返回一个列表。
# 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']
# 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']
注意:对于词典,词典的键将是列表的项。同样,元素的顺序将是随机的。
# 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列表