使用带有 sub-string/similar 个字符串的枚举函数
Using the enumerate function with sub-string/similar strings
正在尝试在两个列表中查找字符串的索引。遇到问题是因为字符串相似。
directories = ['C:/Desktop/5SvF9yM6ldXGRpBz1.csv',
'C:/Desktop/5SvF9yM6ldXGRpBz11.csv',
'C:/Desktop/5SvF9yM6ldXGRpBz12.csv']
barcodes = ['5SvF9yM6ldXGRpBz1',
'5SvF9yM6ldXGRpBz11',
'5SvF9yM6ldXGRpBz12']
输出如下。如何获得第一个条形码 '5SvF9yM6ldXGRpBz1' = [0] 而不是 [0,1,2]
5SvF9yM6ldXGRpBz1
[0, 1, 2]
5SvF9yM6ldXGRpBz11
[1]
5SvF9yM6ldXGRpBz12
[2]
您应该考虑以下几点
from os.path import basename, splitext
[[i for k in barcodes if k==splitext(basename(j))[0]] for i,j in enumerate(directories)]
[[0], [1], [2]]
或者您可以使用正则表达式:
import re
[[i for k in barcodes if re.sub('.*/(\w+).*','\1',j)==k] for i,j in enumerate(directories)]
[[0], [1], [2]]
[[i for k in barcodes if re.sub('.*/|\..*','',j)==k] for i,j in enumerate(directories)]
[[0], [1], [2]]
正在尝试在两个列表中查找字符串的索引。遇到问题是因为字符串相似。
directories = ['C:/Desktop/5SvF9yM6ldXGRpBz1.csv',
'C:/Desktop/5SvF9yM6ldXGRpBz11.csv',
'C:/Desktop/5SvF9yM6ldXGRpBz12.csv']
barcodes = ['5SvF9yM6ldXGRpBz1',
'5SvF9yM6ldXGRpBz11',
'5SvF9yM6ldXGRpBz12']
输出如下。如何获得第一个条形码 '5SvF9yM6ldXGRpBz1' = [0] 而不是 [0,1,2]
5SvF9yM6ldXGRpBz1
[0, 1, 2]
5SvF9yM6ldXGRpBz11
[1]
5SvF9yM6ldXGRpBz12
[2]
您应该考虑以下几点
from os.path import basename, splitext
[[i for k in barcodes if k==splitext(basename(j))[0]] for i,j in enumerate(directories)]
[[0], [1], [2]]
或者您可以使用正则表达式:
import re
[[i for k in barcodes if re.sub('.*/(\w+).*','\1',j)==k] for i,j in enumerate(directories)]
[[0], [1], [2]]
[[i for k in barcodes if re.sub('.*/|\..*','',j)==k] for i,j in enumerate(directories)]
[[0], [1], [2]]