【问题标题】:Convert a set to a list in Python 2.7.8在 Python 2.7.8 中将集合转换为列表
【发布时间】:2014-11-24 13:31:59
【问题描述】:

试图进一步适应 stackoverflow 上的这个问题:

How to convert a set to a list in python?

我一直在尝试解决this riddle on interactivepython.org这个谜题就在页面的末尾,它就像......

我们有一个列表,例如list1 = ['cat','dog','rabbit'],现在使用列表推导(严格来说是列表推导),我们必须在 list1 中的每个单词中创建每个字母的列表,并且结果列表不应包含重复项。

所以预期的答案是这样的:

['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

即使不保持顺序也没关系。

现在首先创建一个所有字符的列表,使用:

print [word[i] for word in list1 for i in range(len(word))]

它给出了输出

['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']

这也包括重复项

然后我将它创建到集合中,因为集合不包含重复项:

print set([word[i] for word in list1 for i in range(len(word))])

输出:

set(['a', 'c', 'b', 'd', 'g', 'i', 'o', 'r', 't'])

然而,这会返回一个集合而不是一个列表,并且可以通过以下方式进行验证:

type(set([word[i] for word in list1 for i in range(len(word))]))

输出:

<type 'set'>

现在,在上面给出的interactivepython.org链接的视频中,这个家伙只是将print之后的整个内容包含在list()中,如下所示:

print list(set([word[i] for word in list1 for i in range(len(word))]))

他在列表中得到了结果输出,但是当我尝试使用使用 python 2.7.8 的空闲时,我没有得到相同的结果。相反,它给了我一个错误:

Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    print list(set([word[i] for word in list1 for i in range(len(word))]))
TypeError: 'list' object is not callable

我认为这可能是因为交互式 python 使用 Python 3 作为其教程。那么这仅仅是 Python 3 和 Python 2.7 之间的区别吗?

另外,如何使用 Python 2.7.8 实现类似的输出

谢谢

【问题讨论】:

  • 如果这不完全违反规则,我会选择list(set().union(*list1)) - 这适用于 2.x 和 3.x

标签: list python-2.7 set


【解决方案1】:

python 2.7 中我们可以使用 list(set) 将 set 转换为 list

>>> a=set([1,2,3])
>>> a
set([1, 2, 3])
>>> b=list(a)
>>> b
[1, 2, 3]
>>> 

我认为 python 3 也具有相同的功能

【讨论】:

    【解决方案2】:

    所有 Python 版本都支持通过语法 list(&lt;iterable&gt;) 创建列表,因此您的特定 Python 版本不是导致错误的原因。

    我认为你在the accepted answer中对你提供的链接问题犯了类似的错误,即在你的交互式shell中你定义了一个名为list的变量,它隐藏了内置类型list .

    例如,在 Python 2.7.6 上:

    >>> list({1, 2, 3}) # successfully convert a set to a list
    [1, 2, 3]
    >>> list = []       # shadow the built-in type list
    >>> list({1, 2, 3}) # this fails since list no longer references the built-in type
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'list' object is not callable
    

    尝试退出你的 shell 并重新进入它,执行相同的命令,看看它们是否有效。


    在不相关的注释中,您可以进一步改进您的列表生成:

    [word[i] for word in list1 for i in range(len(word))]
    

    到这里:

    [letter for word in list1 for letter in word]
    

    因为遍历一个字符串会一一返回它的字符。其实这也是@JonClements精明解决方案背后的底层逻辑:

    list(set().union(*list1))
    

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 2011-09-29
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多