使用Python获取与for循环中另一个列表的项匹配的列表项

时间:2017-03-01 05:01:17

标签: python list loops

我是Python新手,所以首先对不起,如果我问一些太明显的东西......我有一个字符串列表,如:

a = ['car/red/1','car/red/2','bike/red/1','bike/red/3','skate/blue/1','skate/blue/2']

另一个包含子串的列表:

b = ['car/red','bike/red','skate/blue']

如何在每次b中项目的匹配时迭代列表“a”? 我想要这样的东西:

for i in b: matches = [x for x in a if i in x] print matches

所以第一次打印将打印'car / red / 1'和'card / red / 2',第二次打印'bike / red / 1'和'bike / red / 3',第三次打印打印'skate / blue / 1'和'skate / blue / 2'。

3 个答案:

答案 0 :(得分:0)

for item in b:
    print [x for x in a if item in x]

以上将返回

['car/red/1', 'car/red/2']
['bike/red/1', 'bike/red/3']
['skate/blue/1', 'skate/blue/2']

我们遍历b中的每个b_item,然后使用list comprehension打印来自a的任何a_item的新数组,其中b_item是子字符串

答案 1 :(得分:0)

不确定这是否有帮助。我知道必须有更精确的方法。但是试试下面的代码

a = ['car/red/1','car/red/2','bike/red/1','bike/red/3','skate/blue/1','skate/blue/2']

b = ['car/red','bike/red','skate/blue']

for i in a:
    for j in b:
        if i in j:
            print j

答案 2 :(得分:0)

根据您的期望,我可能想要使用startwith。

a = ['car/red/1','car/red/2','bike/red/1','bike/red/3','skate/blue/1','skate/blue/2']
b = ['car/red','bike/red','skate/blue']

for ii in b:
    matches = [x for x in a if x.startswith(ii)]
    print(matches)

结果如下:

['car/red/1', 'car/red/2']
['bike/red/1', 'bike/red/3']
['skate/blue/1', 'skate/blue/2']