arrays - Slicing a python string with intervals? -
i have string a="2:1,3:2,4:5,7:5" want split , assign 2,3,4,7 integer list , 1,2,5,5 other.i tried b=a.split(":") first , c=b.split(",").i 21,32 etc.
so can suggest way i'm way in on head.
i'm not sure how possibly 21 out of remotely used.
but you're on right track. let's go through step step.
>>> a="2:1,3:2,4:5,7:5" >>> b=a.split(":") >>> b ['2', '1,3', '2,4', '5,7', '5'] ok, isn't right, because wanted 2 , 1 first, 3 , 2, , on.
>>> b=a.split(',') >>> b ['2:1', '3:2', '4:5', '7:5'] ok, want split each thing in list. how that? write for loop, or use map, list comprehension simplest:
>>> c=[element.split(':') element in b] [['2', '1'], ['3', '2'], ['4', '5'], ['7', '5']] now you've got 2 lists, they're zipped together. how unzip them? zipping!
>>> d, e = zip(*c) >>> d ('2', '3', '4', '7') >>> e ('1', '2', '5', '5') now, you're there, want these lists of integers, rather tuples of strings. list comprehensions again rescue:
>>> f = [int(element) element in d] >>> g = [int(element) element in e] >>> f [2, 3, 4, 7] >>> g [1, 2, 5, 5]
Comments
Post a Comment