打印频繁值时修复代码,python

Fixing code when printing frequent values, python

相关

我为示例制作了一个演示列表, 运行 它带有“for i in range (len(lines))”:

from statistics import multimode
lines = [[0,1],[1,5],[1,3],[67,45],[98,23],[67,68],[23,2],[1,18],[23,67],[40,79],[40,234],[40,41],[41,51]]

most = multimode(item for sublist in lines for item in sublist)
for a in most:
    del_connected = [bin for bin in lines if a in bin] # these connected to the maximum occured 
    for i, k in del_connected:
        lines = [x for x in lines if k not in x]
        lines = [x for x in lines if i not in x]
print(lines)

第一轮只有一个值"1"出现,第二轮有3个:41,23,67。这就是为什么我做了一个 for 循环并将“most”匹配到“a”但是 del_connected 打印了错误的值,所以“lines”列表本身 -->

>>[[67, 45], [67, 68], [23, 67]]
>>[]
>>[[40, 79], [40, 234], [40, 41]]

当有多个频繁值时,如何修复它的打印?

你想要这样的东西吗:

lines = ...

while len(lines) > 0:
    print(lines)
    most = multimode(item for sublist in lines for item in sublist)
    connected = [
        bin
        for bin in lines
        for a in most
        if a in bin
    ]
    for i, k in connected:
        lines = [
            bin
            for bin in lines
            if (i not in bin) or (k not in bin)
        ]