打印列表时避免使用链式数字

2024-04-26 11:21:02 发布

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

我创建的代码从组合中生成了一个包含15个数字的列表,因此在排序之后,可能会看到一些序列包含大量的数字,例如:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 20]

我正在想一种方法来控制它,只打印最多有4个链式数字的列表:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 20]

(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) >>>> 11 Chained numbers: 1 to 11.
So it won't be stored in file.txt.


[1, 2, 3, 6, 7, 8, 9, 11, 12, 16, 17, 18, 19, 22, 23]

(1, 2, 3) >>>> 3 chained, OK
(6, 7, 8, 9) >>>> 4 chained, OK
(11, 12) >>>> 2 chained, OK
(16, 17, 18, 19) >>>> 4 chained, OK
(22,23) 2 chained, OK. 
So this list will be stored in the file

你们能给我个主意吗?一盏灯?你知道吗

我创建的代码,它生成了一个包含25个数字列表中15个数字的所有可能组合的文件:

import itertools
my_file = open('file.txt', 'w')

ALL_25 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]

for subset in itertools.combinations(ALL_25, 15):
    sort_subsets = sorted(subset)
    my_file.write("{0}\n".format(sort_subsets))  
    print(sort_subsets)
my_file.close()

Tags: 代码intxt列表somyok数字
1条回答
网友
1楼 · 发布于 2024-04-26 11:21:02

如果可以将链转换为连续元素之间的差异,则更容易识别增量序列,即[1,2,3,4,7,8]转换为[1,1,1,3,1]。此外,通过将其转换为字符串,可以更容易地搜索模式111。你知道吗

import numpy as np                                          
import re                                                   

def validate(seq):                                          
    stl = "".join(np.diff(seq).astype(str))                 
    for x in re.findall("[1]+",stl):                        
        if len(x)>3:                                        
            return False                                    
    return True                                             

print validate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 20])
print validate([1, 2, 3, 6, 7, 8, 9, 11, 12, 16, 17, 18, 19, 22, 23])

输出

False
True

相关问题 更多 >