[英]get items of a list that matches items of another list in a for loop with Python
I'm really new to Python so first of all sorry if I'm asking something too obvious... I have a list of strings like: 我对Python真的很陌生,所以首先抱歉,如果我问的太明显了...我有一个字符串列表,例如:
a = ['car/red/1','car/red/2','bike/red/1','bike/red/3','skate/blue/1','skate/blue/2']
And another list with substrings like: 另一个带有子字符串的列表,例如:
b = ['car/red','bike/red','skate/blue']
How can I iterate list "a" extracting everytime the matches of an item in b? 每当b中某项匹配时,如何迭代列表“ a”提取? I want something like: 我想要类似的东西:
for i in b: matches = [x for x in a if i in x] print matches
So the first pass of this would print 'car/red/1' and 'card/red/2', the second would print 'bike/red/1' and 'bike/red/3' and the third would print 'skate/blue/1' and 'skate/blue/2'. 因此,第一遍将打印“ car / red / 1”和“ card / red / 2”,第二遍将打印“ bike / red / 1”和“ bike / red / 3”,第三遍将打印“ skate” / blue / 1”和“ skate / blue / 2”。
for item in b:
print [x for x in a if item in x]
The above will return 以上将返回
['car/red/1', 'car/red/2']
['bike/red/1', 'bike/red/3']
['skate/blue/1', 'skate/blue/2']
We are traversing each b_item in b
and then using list comprehension to print a new array of any a_item from a
of which b_item is a substring 我们遍历每个b_item b
,然后使用列表解析打印任何a_item的新阵列从a
其中的b_item是一个子
Not sure if this would help. 不知道这是否有帮助。 I know there must be more precise approach. 我知道必须有更精确的方法。 But give the following code a try 但是尝试下面的代码
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
Based on your expectation, I might want to use startwith. 根据您的期望,我可能要使用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)
Result is the following: 结果如下:
['car/red/1', 'car/red/2']
['bike/red/1', 'bike/red/3']
['skate/blue/1', 'skate/blue/2']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.