Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python列表元组_Python_List_Dictionary_Tuples - Fatal编程技术网

Python列表元组

Python列表元组,python,list,dictionary,tuples,Python,List,Dictionary,Tuples,说 列表不是没有必要吗?我认为,排序(data.items())本身将返回元组的列表?为什么会有人专门使用列表函数 是的,在这种情况下它是不必要的:-)在这种情况下,列表调用是不必要的,您是正确的 有些Python方法返回迭代器而不是列表。list函数可用于强制迭代器成为list(例如,这样它就可以被索引) 以返回迭代器的函数为例: data = { 123: 1, 234: 2, 241: 4 } a = list(sorted(data.items())) 我们可以使用list使用迭代器并


列表不是没有必要吗?我认为,
排序(data.items())
本身将返回
元组的
列表?为什么会有人专门使用列表函数

是的,在这种情况下它是不必要的:-)

在这种情况下,
列表
调用是不必要的,您是正确的

有些Python方法返回迭代器而不是列表。
list
函数可用于强制迭代器成为list(例如,这样它就可以被索引)

以返回迭代器的函数为例:

data = { 123: 1, 234: 2, 241: 4 }
a = list(sorted(data.items()))
我们可以使用
list
使用迭代器并在列表中使用其结果:

In [1]: type(reversed([3,1,2]))
Out[1]: listreverseiterator

In [2]: reversed([3,1,2])[1]
---------------------------------------------------------------------------
TypeError: 'listreverseiterator' object has no attribute '__getitem__'
list
可用于强制其他类似列表的类型成为具体列表:

In [3]: list(reversed([3,1,2]))[1]
Out[3]: 1

是,
sorted
返回一个
列表本身。因此,在
list
数据结构上调用
list()
是没有用的。对其调用
list()
相当于
sorted(data.items())[:]

In [4]: (1,2,3).append(4)
---------------------------------------------------------------------------
AttributeError: 'tuple' object has no attribute 'append'

In [5]: list((1,2,3)).append(4) # => [1, 2, 3, 4]
如果要获取
迭代器的所有值,则
list()
非常有用:

In [7]: print sorted.__doc__
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

In [8]: lis=[1,2,3]

In [9]: lis
Out[9]: [1, 2, 3]

In [10]: list(lis)    #same result, but different object. (A shallow copy)
Out[10]: [1, 2, 3]

在这种情况下是没有必要的。那么问题是什么?+1。OP问题的关键可能是,无论是谁编写的
sorted
是否返回一个列表都不是肯定的,他没有考虑它,也没有在解释器中测试它,而是决定添加一个额外的
list
以确保安全。IIRC,
sorted
返回Python 3中的生成器视图,因此,在这种情况下,用调用
list
来包装它是很有用的。(编辑:似乎我错了:与许多其他函数不同,
sorted
即使在Python 3.3中仍然返回列表)
In [11]: y=xrange(5)

In [12]: y
Out[12]: xrange(5)

In [13]: list(y)
Out[13]: [0, 1, 2, 3, 4]