开发者

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜