list - 在 Python 2.7.8 中将集合转换为列表

标签 list python-2.7 set

尝试进一步适应 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 实现类似的输出

谢谢

最佳答案

我们可以在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 也具有相同的功能

关于list - 在 Python 2.7.8 中将集合转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26112061/

相关文章:

arrays - 在格上有效地计算邻居的功能

python - 查找包含特定文本的 HTML 标记

java - 三合会不出现战斗? (Java Set 缺少一项)

java - 集合的 "toArray"是确定性的吗?

java - 有没有一种方法可以按照传递的顺序从集合中恢复对象?

list - 按列表子集 data.frame 并按行在每个部分上应用函数

python - 属性错误 : list object has no attribute 'apply'

python - 有没有办法进一步减少 '' 这个 python 代码中的 for 循环?

python覆盖上一行

python - Python 2.7 中的 turtle 图形 : Drawing an arc