python - 如何将工作字典排序程序转换为 Python 3.5

标签 python sorting python-3.x dictionary set

我是 Python 新手(4 周后),我的 Python 程序在对我的字典进行排序时遇到了问题。我的字典中有 ID,其中一些 ID 是相互连接的(通过集合)。在这个例子中,我应该得到一个由两个数组 [[1,3,4,7,8,9],[2,5,6,50,70,80]] 组成的数组来标记我的两个不同的组。 这个程序在较旧的 python 版本上运行,但现在我在将其转换为 Python 3.5 时遇到问题,因为这些集合的工作方式不同,而且我似乎无法运行它。我需要更改什么才能使其在 Python 3.5 上运行? (我在 Spyder 环境中使用 WinPython 3.5)

from sets import Set
dict = {1:Set([3,4]), 2:Set([5,6]), 3:Set([1,4,7,8]), 4:Set([1,3,8,9]), 5:Set([2,6,50,80]), 6:Set([2,5,70,80]), 7:Set([3,8]), 8:Set([3,4,7,9]), 9:Set([4,8]), 50:Set([5,80]), 70:Set([6,80]), 80:Set([5,6,50,70])}

def recursion(number):
    if number not in tmp_array:
        tmp_array.append(number)
        if number in dict:
            tmp = dict[number]
            del dict[number]
            for i in tmp:
                recursion(i)

def startRecursion(number):
    global tmp_array
    tmp_array = []
    recursion(number)
    return tmp_array

def getResults():
    results = []
    tmp_array = []
    while dict:
        results.append(startRecursion(dict.keys()[0]))
    return results

print (getResults())

最佳答案

Python 将 sets 模块替换为 a built-in set type在2.4版本中。要切换到新类型,只需删除 from sets import Set 行并将每次出现的 Set 更改为 set 即可。另请注意,set([3,4]) 现在可以等效地编写为 {3,4}

关于python - 如何将工作字典排序程序转换为 Python 3.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35014699/

相关文章:

python - sqlalchemy 外键关系属性

c - 我的 C 程序出了什么问题?这是关于指针和选择排序的

python-3.x - 使用 pytest,如何将 pathlib 的 Path.isdir() 函数与 os.listdir 一起模拟

python - 如何使用 Python tkinter 创建子窗口?

python - 如何通过python中的代理 Selenium 访问国家/地区受限网站

python快速获取较大列表中也存在于较小列表中的元素的索引

c++ - 使用排序函数对并行数组进行排序

search - 如何在Octave中对(字符串的)单元格数组中的元素进行排序和有效查找?

python - 我无法在 python 3.8 中使用tensorflow

python - 从Python 3中的类对象调用成员方法