我有以下聽寫串列:
money_line = [
{
"id": 1,
"book": "SPORT_888"
},
{
"id": 2,
"book": "WYNN"
},
{
"id": 3,
"book": "BET_RIVERS_VA"
},
{
"id": 4,
"book": "WILLIAM_HILL"
{
"id": 5,
"book": "SUGAR_HOUSE_NJ"
},
{
"id": 6,
"book": "WYNN_NY"
}
]
以及以下字串串列:
list_to_remove = ["SPORT_888", "WYNN", "MGM"]
如您所見,在 dict 值中,我在“WYNN_NY”專案上有一個后綴。我需要從 money_line 中洗掉 list_to_remove 中的所有專案,忽略后綴。
已經嘗試過:
live_money_line = [i for i in money_line if i['book'].rsplit('_', 1)[0] not in list_to_remove]
但這會洗掉“888”“SPORT_888”,這不是我需要的結果。
也試過:
for code in list_to_remove:
for item in money_line:
if code in item['book']:
money_line.remove(item)
但由于某種原因,它無法正常作業。它在 money_line 串列中保留了錯誤的專案。
我在這個 for 回圈中遺漏了什么,還是有更好的方法來完成這項作業?
期望的結果:
money_line = [
{
"id": 3,
"book": "BET_RIVERS_VA"
},
{
"id": 4,
"book": "WILLIAM_HILL"
{
"id": 5,
"book": "SUGAR_HOUSE_NJ"
}
]
uj5u.com熱心網友回復:
您可以使用startswith()andany()一起過濾掉不需要的字典:
money_line = [
{
"id": 1,
"book": "SPORT_888"
},
{
"id": 2,
"book": "WYNN"
},
{
"id": 3,
"book": "BET_RIVERS_VA"
},
{
"id": 4,
"book": "WILLIAM_HILL"
},
{
"id": 5,
"book": "SUGAR_HOUSE_NJ"
},
{
"id": 6,
"book": "WYNN_NY"
}
]
list_to_remove = ["SPORT_888", "WYNN", "MGM"]
[d for d in money_line if not any(d['book'].startswith(token) for token in list_to_remove)]
結果是:
[{'id': 3, 'book': 'BET_RIVERS_VA'},
{'id': 4, 'book': 'WILLIAM_HILL'},
{'id': 5, 'book': 'SUGAR_HOUSE_NJ'}]
uj5u.com熱心網友回復:
如果您更喜歡理解(新的字典串列):
d = [d for d in money_line if not any(d['book'].startswith(prefix) for prefix in list_to_remove)]
如果您更喜歡帶有洗掉(就地)的回圈:
for i in reversed([i for i, d in enumerate(money_line)
if any(d['book'].startswith(prefix) for prefix in list_to_remove)]):
del money_line[i]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414107.html
標籤:
上一篇:如何將嵌套集轉換為串列?
