输入:
sorted list,像这样:[1,2,3,8,10,15,16,17,18,22,23,27,30,31]max_diff = 2预期产量:
[[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) 在下面的代码中,我想计算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) 我想使用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)
发现当作业号为几千时,该脚本将花费很长时间来输出信息.
有没有办法提高效率?
谢谢!