编辑:添加解决方案.
嗨,我目前有一些工作虽然代码很慢.
它使用主键逐行合并2个CSV文件.例如,如果文件1具有以下行:
"one,two,,four,42"
Run Code Online (Sandbox Code Playgroud)
和文件2有这一行;
"one,,three,,42"
Run Code Online (Sandbox Code Playgroud)
其中0索引$ position = 4主键= 42;
然后是sub:merge_file($ file1,$ file2,$ outputfile,$ position);
将输出一行文件:
"one,two,three,four,42";
Run Code Online (Sandbox Code Playgroud)
每个主键在每个文件中都是唯一的,一个键可能存在于一个文件中但不存在于另一个文件中(反之亦然)
每个文件大约有100万行.
通过第一个文件中的每一行,我使用哈希来存储主键,并将行号存储为值.行号对应于存储第一个文件中每一行的数组[行号].
然后我遍历第二个文件中的每一行,并检查主键是否在哈希中,如果是,则从file1array获取行,然后将我需要的列从第一个数组添加到第二个数组,并且然后结束.到最后.然后删除哈希值,然后在最后,将整个事件转储到文件中.(我正在使用SSD,所以我想最小化文件写入.)
最好用代码解释:
sub merge_file2{
my ($file1,$file2,$out,$position) = ($_[0],$_[1],$_[2],$_[3]);
print "merging: \n$file1 and \n$file2, to: \n$out\n";
my $OUTSTRING = undef;
my %line_for;
my @file1array;
open FILE1, "<$file1";
print "$file1 opened\n";
while (<FILE1>){
chomp;
$line_for{read_csv_string($_,$position)}=$.; #reads csv line at current position (of key)
$file1array[$.] = $_; #store line in file1array.
}
close FILE1;
print "$file2 opened - merging..\n";
open …Run Code Online (Sandbox Code Playgroud) 我想优化这个Perl子:
push_csv($string,$addthis,$position);
用于将字符串放在CSV字符串中.
例如,如果$string="one,two,,four"; $addthis="three"; $position=2;
那时push_csv($string,$addthis,$position)将改变的价值$string = "one,two,three,four";
sub push_csv {
my @fields = split /,/, $_[0]; # split original string by commas;
$_[1] =~ s/,//g; # remove commas in $addthis
$fields[$_[2]] = $_[1]; # put the $addthis string into
# the array position $position.
$_[0] = join ",", @fields; # join the array with commas back
# into the string.
}
Run Code Online (Sandbox Code Playgroud)
这是我的代码中的瓶颈,因为它需要被称为几百万次.
如果你精通Perl,你能看看它,并提出优化/替代方案吗?提前致谢!:)
编辑:转换为@fields并返回字符串需要时间,我只想到一种方法来加快它我连续多个子调用.拆分一次,然后将多个东西推入阵列,然后在最后加入一次.
我想合并两个列表:
a = [1,2,3,4,"a"]
b = [1,2,3,4,"b"]
Run Code Online (Sandbox Code Playgroud)
使:
[[1,1], [2,2], [3,3], [4,4], ["a","b"]]
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?
另外,如果可能的话,我还要附加其他列表:
c = [5,6,7,8,"c"]
Run Code Online (Sandbox Code Playgroud)
要得到
[[1,1,5], [2,2,6], [3,3,7], [4,4,8], [5,5,9], ["a","b","c"]
Run Code Online (Sandbox Code Playgroud)
您可以假定列表的长度相同。
示例代码
list = [i.get('content').encode('utf-8') for i in self.soup.find_all('meta',attrs={"name": "description"})]
Run Code Online (Sandbox Code Playgroud)
问题是.encode('utf-8')会引发错误:
AttributeError: 'NoneType' object has no attribute 'encode'
Run Code Online (Sandbox Code Playgroud)
如果列表中的一个元素是None.
我想知道是否有一种'pythonic'方式将它保持在一行并忽略None元素.例如,您可以if not None在列表中放置一个子句吗?谢谢.