我有一系列相同长度的24个字符的字符串,如
my_series = ['ThisIsASentenceXXXXXXXXX', 'SoIsThisXXXXXXXXXXXXXXXX', 'YouGetThePointXXXXXXXXXX']
我有一个列表,其长度等于4个字符,如
my_list = ['This', 'XXXX', 'GetT']
我想将my_list中的每个条目与my_series中每个条目中的每个4个字符的块进行比较,并返回找到列表字符串的my_series项。
例如,对于my_list中的字符串'This',我希望my_series项目1和2返回,而'XXXX'my_series项目1,2,3将被返回。
答案 0 :(得分:3)
以下生成器将创建一个二维列表。每个列表将包含任何匹配项,并且它的位置将与my_list索引匹配。
n_list = [[x for x in my_series if item in x] for item in my_list]
输出:
[[' ThisIsASentenceXXXXXXXXX&#39 ;,' SoIsThisXXXXXXXXXXXXXXXX'],[' ThisIsASentenceXXXXXXXXX&#39 ;,' SoIsThisXXXXXXXXXXXXXXXX&#39 ;,' YouGetThePointXXXXXXXXXX&#39 ;],[' YouGetThePointXXXXXXXXXX']]
因此n_list[0]
包含my_list[0]
等的匹配项...
我希望这能帮到你!
答案 1 :(得分:-1)
您需要将my_series
中的每个条目拆分为6个块:
serires_chunks = [(s[0:4], s[4:8], s[8:12], s[12:16], s[16:20], s[20:24])
for s in my_series]
然后你可以迭代这个块来找到匹配的项目:
for item in my_list:
for index, chunks in enumerate(serires_chunks):
for place, chunk in enumerate(chunks, 1):
if item == chunk:
location = my_series[index]
print("Found '{item}' in '{location}' at {place}".format(**locals()))
您将获得:
Found 'This' in 'ThisIsASentenceXXXXXXXXX' at 1
Found 'This' in 'SoIsThisXXXXXXXXXXXXXXXX' at 2
Found 'XXXX' in 'ThisIsASentenceXXXXXXXXX' at 5
Found 'XXXX' in 'ThisIsASentenceXXXXXXXXX' at 6
Found 'XXXX' in 'SoIsThisXXXXXXXXXXXXXXXX' at 3
Found 'XXXX' in 'SoIsThisXXXXXXXXXXXXXXXX' at 4
Found 'XXXX' in 'SoIsThisXXXXXXXXXXXXXXXX' at 5
Found 'XXXX' in 'SoIsThisXXXXXXXXXXXXXXXX' at 6
Found 'XXXX' in 'YouGetThePointXXXXXXXXXX' at 5
Found 'XXXX' in 'YouGetThePointXXXXXXXXXX' at 6