How to use Python slice to extract a list of positions in a string
I have two strings:
a='1234512345'
b='abcdefghik'
I would like to search string "a" for occurrences of '1' and then print the positions of "b" that correspon开发者_开发技巧d to that index, i.e.
'af'
I can use
import re
starts=[match.start() for match in re.finditer(re.escape('1'), a)]
to find that '1' occurs in positions [0,5]. How would I use this info to extract 'af' from string "b"
You could do something like this:
''.join(b[x] for x in starts)
But I would recommend this instead:
a='1234512345'
b='abcdefghik'
''.join(y for (x, y) in zip(a, b) if x == '1')
>>> a='1234512345'
>>> b='abcdefghik'
>>> [ j for i,j in zip(a,b) if i=="1" ]
['a', 'f']
In [11]: a='1234512345'
In [12]: b='abcdefghik'
In [16]: ''.join(b[i] for i,num in enumerate(a) if num=='1')
Out[16]: 'af'
or, if you really want to use regex:
In [21]: ''.join(b[match.start()] for match in re.finditer(re.escape('1'), a))
Out[21]: 'af'
import re
a='1234512345'
b='abcdefghik'
starts= [ b[i] for i in [ match.start() for match in re.finditer(re.escape('1'), a)]]
print ''.join(starts)
"".join(b[i] for i in range(min(len(a), len(b))) if a[i] == "1")
like this?
a='1234512345'
b='abcdefghik'
for char in a:
n = -1
for subc in a:
n=n+1
if subc == char:
print b[n],
print
produces:
a f
b g
c h
d i
e k
a f
b g
c h
d i
e k
If you have to repeat this for a few values of a
, it will be more efficient ((O(n)) to build a dictionary than to loop through a
and b
repeatedly (O(n*n))
>>> a='1234512345'
>>> b='abcdefghik'
>>> from collections import defaultdict
>>> D=defaultdict(str)
>>> for i,j in zip(a,b):
... D[i]+=j
...
>>> D['1']
'af'
>>> D['2']
'bg'
精彩评论