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

2024-10-04 05:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表,其中列表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)

我知道我可以做一些类似“如果我在B中,那么我在A中为I”的事情,但是我不知道将匹配值放入字典的语法

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

编辑:我在示例中犯了一个错误:我正在处理的实际列表和字符串并不都使用前缀。我不确定这些答案中是否有不同的方法,但我很感激所有的回答。我想要解析的字符串是URL和URL的一部分。所以A充满了'NA1234'类型的字符串,B则是'www.oops/NA1244/betterexample'


Tags: 字符串元素列表prefix字典ziptridict
2条回答

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

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)]

相关问题 更多 >