用另一个列表遍历一个列表



我有两个列表,其中列表A的元素包含在列表b的元素中。注意,这个例子中的顺序是相当重要的。

A = ['pent', 'tri', 'rec', 'oct', 'hex']
B = ['triangle', 'rectangle', 'pentangle', 'hexagon', 'octagon']

我想遍历A和B,在B中找到A的地方,将它添加到字典中,然后将它添加到字典中。

d = {'prefix': a, 'shape':b}
l = [{'prefix': 'pent', 'shape':'pentangle'}, {'prefix':'tri' , 'shape':'triangle'}, {'prefix': 'rec', 'shape':'rectangle'},...]

我尝试使用zip函数,但我认为因为B相对于A是无序的,它不起作用

dict_list = []
for i,j in zip(A,B):
if i in j:
d = {'prefix': i, 'shape':j}
dict_list.append(d)

我知道我可以这样写"for I in A if I in "但是我不知道如何将匹配的值输入到我的字典中。

我认为这是一个非常基本的问题,我只是还没能让它工作。这应该与zip工作吗?我想也有可能预先填充前缀,然后以某种方式使用它来找到形状,但是,我不确定语法。在某些情况下,我使用的列表有1000多条记录,所以我不能手动执行此操作。

编辑:我在我的例子中犯了一个错误:我正在使用的实际列表和字符串并不都使用前缀。我不确定是否可以在这些答案中加入不同的方法,但我感谢所有的回应。我要解析的字符串是url和url的一部分。所以A是全'NA1234'类型字符串,B是'www.oops/NA1244/betterexample'类型字符串。

可以使用列表推导式。这可能不是最有效的方法,但至少语法很容易理解。

A = ['pent', 'tri', 'rec', 'oct', 'hex']
B = ['triangle', 'rectangle', 'pentangle', 'hexagon', 'octagon']
dict_list = [{'prefix': a, 'shape': b} for a in A for b in B if b.startswith(a)]
print(dict_list) # [{'prefix': 'pent', 'shape': 'pentangle'}, {'prefix': 'tri', 'shape': 'triangle'}, {'prefix': 'rec', 'shape': 'rectangle'}, {'prefix': 'oct', 'shape': 'octagon'}, {'prefix': 'hex', 'shape': 'hexagon'}]

您可以尝试使用生成器进行列表推导:

[{'prefix': x, 'shape': next(y for y in B if y.startswith(x))} for x in A]

输出:

[{'prefix': 'pent', 'shape': 'pentangle'},
{'prefix': 'tri', 'shape': 'triangle'},
{'prefix': 'rec', 'shape': 'rectangle'},
{'prefix': 'oct', 'shape': 'octagon'},
{'prefix': 'hex', 'shape': 'hexagon'}]

或者您可以先将B排序为与A相同的顺序:

B = sorted(B, key=lambda x: next(i for i, v in enumerate(A) if x.startswith(v)))

然后输入zip:

[{'prefix': x, 'shape': y} for x, y in zip(A, B)]