[英]get items of a list that matches items of another list in a for loop with Python
我對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”。
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_item b
,然后使用列表解析打印任何a_item的新陣列從a
其中的b_item是一個子
不知道這是否有幫助。 我知道必須有更精確的方法。 但是嘗試下面的代碼
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
根據您的期望,我可能要使用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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.