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

S.S*_*sky 4 python dictionary python-3.x

我有两个列表,其中列表 A 的元素包含在列表 B 的元素中。请注意,此示例中的顺序相当重要。

A = ['pent', 'tri', 'rec', 'oct', 'hex']
B = ['triangle', 'rectangle', 'pentangle', 'hexagon', 'octagon']
Run Code Online (Sandbox Code Playgroud)

我想遍历A和B,无论在B中找到A,将其添加到字典中,然后将其添加到字典中。

d = {'prefix': a, 'shape':b}

l = [{'prefix': 'pent', 'shape':'pentangle'}, {'prefix':'tri' , 'shape':'triangle'}, {'prefix': 'rec', 'shape':'rectangle'},...]
Run Code Online (Sandbox Code Playgroud)

我尝试使用 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)
Run Code Online (Sandbox Code Playgroud)

我知道我可以做类似“for i in A if i in B”之类的事情,但我不知道将匹配值放入字典的语法。

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

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

j1-*_*lee 5

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

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'}]
Run Code Online (Sandbox Code Playgroud)

  • @S.Slusky 当然,你可以把 `a in b` 而不是 `b.startswith(a)` 。 (2认同)