Python:我的集合是如何变成一个列表的?

2024-09-30 03:23:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一个程序来递归地获取wordnet图形中给定语法集的所有下义子词。你知道吗

然而,这与我这里的问题无关。你知道吗

我基本上是把我通过的所有节点添加到一个集合中。 然而,我得到的输出是一个列表

这是我的密码

import pickle
import nltk
from nltk.corpus import wordnet as wn

feeling = wn.synset('feeling.n.01')
happy = wn.synset('happiness.n.01')

def get_hyponyms(li):
    return [x.hyponyms() for x in li]

def flatten(li):
    return [item for sublist in li for item in sublist]

def get_hyponyms_list(li):
    if li:
        return list(set(flatten(get_hyponyms(li))))

def get_the_hyponyms(li, hyps):
    if li:
        hyps |= set(li)
        get_the_hyponyms(get_hyponyms_list(li), hyps)
    return hyps

def get_all_hyponyms(li):
    hyps = set()
    return get_the_hyponyms(li, hyps)

feels = sorted(get_all_hyponyms([feeling]))
print type(feels)

输出如下-

<type 'list'>

为什么会这样?你知道吗


Tags: theinimportforgetreturndefli
1条回答
网友
1楼 · 发布于 2024-09-30 03:23:42

sorted()创建一个列表,如果你做一个简单的测试,这个行为很明显。Pythondocumentation说“set对象是一个无序的、不同的可散列对象的集合”。你知道吗

>>> x = {1,3,2}
>>> sorted(x)
[1, 2, 3]

相关问题 更多 >

    热门问题