我在python中有一个对象数组。如何遍历数组并将任何具有重复名称的对象设置为
valid=False
这是我的测试代码:
class Asset(object):
def __init__(self, name=""):
self.name = name
self.valid = True
items = [
Asset("doug"),
Asset("kevin"),
Asset("kim"),
Asset("kevin")
]
for x in items:
print vars(x)
所以实际上这个测试的结果应该是:
> {'name': 'doug', 'valid': True}
> {'name': 'kevin', 'valid': False}
> {'name': 'kim', 'valid': True}
> {'name': 'kevin', 'valid': False}
答案 0 :(得分:0)
使用hashmaps / dictionary可能是合适的。
class Asset(object):
def __init__(self, name=""):
self.name = name
self.valid = True
items = [
Asset("doug"),
Asset("kevin"),
Asset("kim"),
Asset("kevin")
]
frequency_of_names = {}
for item in items:
name = item.name
if name in frequency_of_names.keys():
frequency_of_names[name] = frequency_of_names[name] + 1
else:
frequency_of_names[name] = 1
for item in items:
if frequency_of_names[item.name] > 1:
item.valid = False
for item in items:
print item.name, item.valid
输出:
doug True
kevin False
kim True
kevin False
答案 1 :(得分:0)
使用列表理解和计数方法:
[OneSignal initWithLaunchOptions:launchOptions appId:ONESIGNAL_APPID handleNotificationReceived:nil handleNotificationAction:nil
settings:@{kOSSettingsKeyInAppAlerts:@NO}];