re beginner

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sun Jun 4 16:47:51 EDT 2006


SuperHik wrote:
> I was wondering is there a better way to do it using re module?
> perheps even avoiding this for loop?

This is a way to do the same thing without REs:

data = 'Yellow hat\t2\tBlue shirt\t1\nWhite socks\t4\tGreen
pants\t1\nBlue bag\t4\tNice perfume\t3\nWrist watch\t7\tMobile
phone\t4\nWireless cord!\t2\tBuilding tools\t3\nOne for the
money\t7\tTwo for the show\t4'

data2 = data.replace("\n","\t").split("\t")
result1 = dict( zip(data2[::2], map(int, data2[1::2])) )

O if you want to be light:

from itertools import imap, izip, islice
data2 = data.replace("\n","\t").split("\t")
strings = islice(data2, 0, len(data), 2)
numbers = islice(data2, 1, len(data), 2)
result2 = dict( izip(strings, imap(int, numbers)) )

Bye,
bearophile




More information about the Python-list mailing list