我有两个列表,其中列表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'
您可以使用列表理解。这可能不是最有效的方法,但至少语法很容易理解
您可以使用生成器尝试列表理解:
输出:
或者您可以首先将
B
排序为与A
相同的顺序:然后
zip
:相关问题 更多 >
编程相关推荐