小编Dra*_*rys的帖子

当两个相邻值差大于阈值时,如何将排序列表拆分为子列表

输入:

  • a sorted list,像这样:[1,2,3,8,10,15,16,17,18,22,23,27,30,31]
  • 一个门槛,像这样: max_diff = 2

预期产量:

  • 子列表列表; 每个子列表包含相邻差异小于max_diff的值,如下所示:[[1, 2, 3], [8, 10], [15, 16, 17, 18], [22, 23], [27], [30, 31]]

这是我如何做到这一点,我想知道是否有更好的方法来做到这一点.

test_list = [1,2,3,8,10,15,16,17,18,22,23,27,30,31]
max_diff = 2

splited_list = []
temp_list = [test_list[0]]
for i in xrange(1,len(test_list)):
    if test_list[i] - temp_list[-1] > max_diff:
        splited_list.append(temp_list)
        temp_list = [test_list[i]]
    else:
        temp_list.append(test_list[i])        
    if i == len(test_list) -1:
        splited_list.append(temp_list)

print splited_list 
Run Code Online (Sandbox Code Playgroud)

python

6
推荐指数
1
解决办法
332
查看次数

listin中list1的Python count元素出现

在下面的代码中,我想计算in word_list中每个单词的出现次数,test下面的代码可以完成这项工作,但可能效率不高,有没有更好的方法呢?

word_list = ["hello", "wonderful", "good", "flawless", "perfect"]
test = ["abc", "hello", "vbf", "good", "dfdfdf", "good", "good"]

result = [0] * len(word_list)
for i in range(len(word_list)):
    for w in test:
        if w == word_list[i]:
            result[i] += 1

print(result)
Run Code Online (Sandbox Code Playgroud)

python list counting

3
推荐指数
1
解决办法
123
查看次数

当文件数量巨大时,如何提高perl中的grep效率

我想使用perl从位于以下目录结构中的日志文件中获取一些日志信息: $jobDir/jobXXXX/host.logwhere XXXX是一个作业号,从1到几千.$jobDir除了日志之外,没有其他类型的子目录,也没有其他文件jobXXXX.该脚本是:

my  @Info;  #store the log informaiton
my $Num = 0;
@Info = qx(grep "information" -r $jobDir); #is this OK ?

foreach(@Info){
        if($_=~ /\((\d+)\)(.*)\((\d+)\)/){
            Output(xxxxxxxx);   
        }
        $Num=$Num+1; #number count      
    }
Run Code Online (Sandbox Code Playgroud)

发现当作业号为几千时,该脚本将花费很长时间来输出信息.

有没有办法提高效率?

谢谢!

regex perl grep

1
推荐指数
2
解决办法
129
查看次数

标签 统计

python ×2

counting ×1

grep ×1

list ×1

perl ×1

regex ×1