我有兩個串列,例如。第一個串列在元素中包含一些額外的字串,但我想找到匹配項,無論是否將其轉換為第二個串列中的整數。
l1 = ['1a','2','3','1b']
l2 = ['1a','4']
輸出要求:
output_requried = ['1a', '1b'] #I need all match that contains 1
試過:
[x for x in l1 if any(y in x for y in l2)]
# It doesn't print "1b", but it can work with ['1','4']
uj5u.com熱心網友回復:
如果您只想比較數字部分,則必須進行一些轉換。
從...開始
l1 = ['1a','2','3','1b']
l2 = ['1a','4']
l2 = [int(''.join(c for c in value if c.isdigit())) for value in l2]
print(l2)
l2現在是[1, 4]。
現在我們使用串列推導來創建匹配。我們遍歷 中的每個值l1,只取值中的數字(就像我們在重新定義 時所做的那樣l2),將它們轉換為整數并檢查它們是否在 中l2。
match = [value for value in l1 if int(''.join(c for c in value if c.isdigit())) in l2]
print(match)
這給了我們['1a', '1b'].
使用函式進行轉換可能有助于理解代碼并確保對值進行相同處理。
def get_int_value(value):
return int(''.join(c for c in value if c.isdigit()))
l1 = ['1a','2','3','1b']
l2 = ['1a','4']
l2 = [get_int_value(value) for value in l2]
match = [value for value in l1 if get_int_value(value) in l2]
print(match)
這是一種簡單的方法,因此"1a2b3"可能會或可能不會按照您的意愿對待像這樣的值。您沒有在問題中指定這一點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/407306.html
標籤:
上一篇:使用串列推導Python將值添加到陣列串列的第一個索引
下一篇:索引為偶數的反向串列
