[英]Finding duplicates from array using Python
我對 Python 很陌生,想知道是否有一種好方法可以創建新的不重復用戶列表。
我的問題是我有這樣的東西
[
{
"userId": "987654321",
"method": "CARD",
"lastDigits": "1234",
"type": "mc",
"first_name": "Leroy",
"last_name": "Jenkins",
"exp": "01/23"
},
{
"userId": "987654321",
"method": "PAYPAL",
"first_name": "Leroy",
"last_name": "Jenkins"
},
{
"userId": "123456789",
"method": "CARD",
"lastDigits": "4567",
"type": "visa",
"first_name": "Joe",
"last_name": "Bloggs",
"exp": "01/25"
},
{
"userId": "46513498000",
"method": "PAYPAL",
"first_name": "Betty",
"last_name": "White"
}
]
基本上我需要在userId
匹配時進行匹配,並在"method": "CARD"
而不是 PAYPAL 時保留PAYPAL
然后再次重建基本相同的列表,但當用戶同時擁有 CARD 和 Z199F4DCF55B9DAFD6AD41CBCFB23 時,減去重復的 userId
::EDIT::用戶只能擁有 PAYPAL。 如果它只有 PAYPAL,只需返回
需要示例 output
[
{
"userId": "987654321",
"method": "CARD",
"lastDigits": "1234",
"type": "mc",
"first_name": "Leroy",
"last_name": "Jenkins",
"exp": "01/23"
},
{
"userId": "123456789",
"method": "CARD",
"lastDigits": "4567",
"type": "visa",
"first_name": "Joe",
"last_name": "Bloggs",
"exp": "01/25"
},
{
"userId": "46513498000",
"method": "PAYPAL",
"first_name": "Betty",
"last_name": "White"
}
]
如果我沒有誤解您的問題,那么簡單的過濾將為您解決問題,
user_ids = []
final_users = []
for user in users:
user_ids.append(int(user['userId']))
if user['userId'] not in user_ids and user['method'] == 'CARD':
final_users.append(user)
print(final_users)
users = {}
for d in user_list:
uid = d["userId"]
# If user id not in users, we add it
if uid not in users:
users[uid] = d
# Otherwise we check if the already recorded method was "PAYPAL",
# if so we overwrite it.
elif users[uid]["method"] == "PAYPAL":
users[uid] = d
# To convert dict we just created back to list:
user_list = list(users.values())
使用defaultdict
:
from collections import defaultdict
newdata = defaultdict(dict)
for item in data:
userid = newdata[item['userId']]
if userid == {} and item['method'] == 'CARD':
userid.update(item)
Output:
# newdata = list(newdata.values())
>>> newdata
[{'userId': '987654321',
'method': 'CARD',
'lastDigits': '1234',
'type': 'mc',
'first_name': 'Leroy',
'last_name': 'Jenkins',
'exp': '01/23'},
{'userId': '123456789',
'method': 'CARD',
'lastDigits': '4567',
'type': 'visa',
'first_name': 'Joe',
'last_name': 'Bloggs',
'exp': '01/25'}]
這將非常適合您。 試試看
mylist=[
{
"userId": "987654321",
"method": "CARD",
"lastDigits": "1234",
"type": "mc",
"first_name": "Leroy",
"last_name": "Jenkins",
"exp": "01/23"
},
{
"userId": "987654321",
"method": "PAYPAL",
"first_name": "Leroy",
"last_name": "Jenkins"
},
{
"userId": "123456789",
"method": "CARD",
"lastDigits": "4567",
"type": "visa",
"first_name": "Joe",
"last_name": "Bloggs",
"exp": "01/25"
},
{
"userId": "46513498000",
"method": "PAYPAL",
"first_name": "Betty",
"last_name": "White"
}
]
temp_list=[]
temp_id=[]
for x in mylist:
if int(x['userId']) not in temp_id:
temp_list.append(x)
temp_id.append(int(x["userId"]))
print(temp_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.