Equivalent of this two line Perl in Python?
I need to find exact equivalent of this two line Perl in Python 2.x
PERL:
foreach my $edge (@edges){
$edge =~ s/[\(\)]//g;
my @verts = sp开发者_如何转开发lit(/,/, $edge);
PYTHON:
for edge in edges:
edge = ???
verts = ???
Thank you very much.
edge = edge.translate(None, '()')
verts = edge.split(',')
You might also want to convert strings to ints in creating verts, using:
verts = map(int, edge.split(','))
Using the regex module to stick closely to the Perl version:
for edge in edges:
edge = re.sub( '[()]', '', edge )
verts = filter( None, re.split( ',', edge ) )
At the top of the script make sure to include
import re
use string methods replace
ans split
(or sub
and split
from re
module). Generally, read about Regular Expressions - most modern languages implementations (int Python too) is based on Perls. And patterns in you're code are very simple:
first you removes all occurrences of '(' and ')', than split line by ',' (as I can tell, I haven't written in perl for years)
精彩评论