python 可迭代对象与迭代器之间的转换

2018-06-18 00:11:09来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 列表:

1 >>> l = [1, 2, 3, 4]
2 >>> l_iter = iter(l)
3 >>> l_iter
4 <list_iterator object at 0x10199e860>
5 >>> l = list(l_iter)
6 >>> l
7 [1, 2, 3, 4]

字符串:

 1 >>> s = 'abcdef'
 2 >>> l = list(s)
 3 >>> l
 4 ['a', 'b', 'c', 'd', 'e', 'f']
 5 >>> i = iter(l)
 6 >>> i
 7 <list_iterator object at 0x10199e8d0>
 8 >>> s = ''.join(l)
 9 >>> s
10 'abcdef'
11 >>> s = ''.join(i)
12 >>> s
13 'abcdef'

字典:

 1 >>> d = dict(one=1, two=2)
 2 >>> d
 3 {'one': 1, 'two': 2}
 4 >>> i = iter(d)
 5 >>> i
 6 <dict_keyiterator object at 0x1019a6458>    # 键值得迭代器
 7 >>> for k in i:
 8 ...     print(k)
 9 ... 
10 one
11 two

元组:

1 >>> t = (1, 2, 3, 4)
2 >>> t_iter = iter(t)
3 >>> t_iter
4 <tuple_iterator object at 0x10199eb00>
5 >>> t = tuple(t_iter)
6 >>> t
7 (1, 2, 3, 4)

集合:

1 >>> s = {1, 2, 3, 4}
2 >>> s_iter = iter(s)
3 >>> s_iter
4 <set_iterator object at 0x1019a5d38>
5 >>> s = set(s_iter)
6 >>> s
7 {1, 2, 3, 4}

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python之路--初识Python

下一篇:Python-Day1