简体   繁体   English

如何使用Python切片提取字符串中的位置列表

[英]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 correspond to that index, ie 我想搜索字符串“a”出现'1',然后打印对应于该索引的“b”的位置,即

'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]. 发现位置[0,5]中出现'1'。 How would I use this info to extract 'af' from string "b" 如何使用此信息从字符串“b”中提取“af”

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 ,这将是更有效的((O(N))来构建字典,而不是通过环ab反复(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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM