Python:单个可迭代`list(x)`与`[x]`的列表 [英] Python: list of a single iterable `list(x)` vs `[x]`

查看:258
本文介绍了Python:单个可迭代`list(x)`与`[x]`的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python似乎在[x]list(x)之间进行区分.为什么会有这种差异?

Python seems to differentiate between [x] and list(x) when making a list object, where x is an iterable. Why this difference?

>>> a = [dict(a = 1)]
>>> [{'a' : 1}]

>>> a = list(dict(a=1))
>>> a = ['a']

虽然第一个表达式似乎可以按预期工作,但是第二个表达式的工作方式更像是迭代dict:

While the 1st expression seems to work as expected, the 2nd expression works more like iterating a dict this way:

>>> l = []
>>> for e in {'a' :1}:
        l.append(e)
>>> l
>>> ['a']

推荐答案

[x]是一个包含元素 x的列表.

[x] is a list containing the element x.

list(x)使用x(必须已经可迭代!)并将其转换为列表.

list(x) takes x (which must already be iterable!) and turns it into a list.

>>> [1]  # list literal
[1]
>>> ['abc']  # list containing 'abc'
['abc']
>>> list(1)
# TypeError
>>> list((1,))  # list constructor
[1]
>>> list('abc')  # strings are iterables
['a', 'b', 'c']  # turns string into list!

列表构造器list(...)-像python的所有内置集合类型(集合,列表,元组,collections.deque等)一样-可以采用一个可迭代的参数并将其转换.

The list constructor list(...) - like all of python's built-in collection types (set, list, tuple, collections.deque, etc.) - can take a single iterable argument and convert it.

这篇关于Python:单个可迭代`list(x)`与`[x]`的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆