[英]Get repeating values in dictionary array. Swift
我有這樣的數組
[
["itm_id": 4, "itm_name": Chicken],
["itm_id": 4, "itm_name": Chicken],
["itm_id": 4, "itm_name": Chicken],
["itm_id": 7, "itm_name": Cat]
]
我有此字典數組,我正在嘗試按字典中的值對它們進行分組。 因此,在上面的示例中,我想知道要創建一個字典來知道我有多少個重復鍵的字典:
[["item_id" : 4, count: 3], ["item_id" : 7, count: 1]]
itm_id: 4
重復3次,因此計數為3, itm_id: 7
僅重復一次。
我該如何實現
我建議您創建項目數組的struct
,而不是像這樣的字典
struct Item{
var itemID : Int
var name : String
init(dictionary:[String:Any]) {
itemID = dictionary["itm_id"] as? Int ?? 0
name = dictionary["itm_name"] as? String ?? ""
}
}
一旦有了Items
數組,就可以將特定項ID的元素映射為數組,以獲取計數並將其從數組中刪除。 看看下面的代碼。 這不是最干凈的實現,但是它將幫助您解決問題。
func countDuplicates(){
let dictionary = [["itm_id": 4, "itm_name": "Chicken"],["itm_id": 4, "itm_name": "Chicken"],["itm_id": 4, "itm_name": "Chicken"],["itm_id": 7, "itm_name": "Cat"]]
var items = [Item]()
var countArray = [[String:Any]]()
dictionary.forEach{
items.append(Item(dictionary: $0))
}
while items.count > 0 {
if let firstItem = items.first{
let duplicateItems = items.filter{$0.itemID == firstItem.itemID}
var countDictionary = [String:Any]()
countDictionary["itm_id"] = firstItem.itemID
countDictionary["count"] = duplicateItems.count
countArray.append(countDictionary)
items = items.filter{$0.itemID != firstItem.itemID}
}
}
print(countArray)
}
這將打印[["itm_id": 4, "count": 3], ["itm_id": 7, "count": 1]]
我以為“ Chicken
,“ Cat
是弦樂器。 如果它們不是字符串而是類類型,則可以將Item
結構重寫為這樣的形式
class Animal{}
class Chicken:Animal{}
class Cat:Animal{}
struct Item<T:Animal>{
var itemID : Int
var name : String
var animal : Animal
init(dictionary:[String:Any],animal:T) {
itemID = dictionary["itm_id"] as? Int ?? 0
name = dictionary["itm_name"] as? String ?? ""
self.animal = animal
}
}
然后您可以像這樣初始化Item
yourItem = Item(dictionary:yourDictionary,animal:Cat())
// Swift 3.1
選項1:使用字典
func countRepeats() -> [[String: Int]] {
var repeats = [Int: Int]()
arr.forEach { item in
if let id = item["itm_id"] as? Int {
repeats[id] = repeats[id] == nil ? 1 : repeats[id]! + 1
}
}
return repeats.map {["item_id" : $0.key, "count": $0.value]}
}
print(countRepeats()) // [["item_id": 4, "count": 3], ["item_id": 7, "count": 1]]
選項2:建議使用Struct代替Dictionary
public struct ItemCount {
let id: Int
let count: Int
}
func countRepeats() -> [ItemCount] {
var repeats = [Int: Int]()
arr.forEach { item in
if let id = item["itm_id"] as? Int {
repeats[id] = repeats[id] == nil ? 1 : repeats[id]! + 1
}
}
return repeats.map {ItemCount(id:$0.key, count: $0.value)}
}
print(countRepeats())
我建議在類(或結構)中處理數據,但是如果必須使用字典數組,則這是獲取計數的一種方法:
// extract all the "itm_id" values from all dictionaries in the array
// use a set to identify unique values
// map each unique values to its count in the array
let ids = dictionaries.flatMap{$0["itm_id"] as? Int}
let idCounts = Set(ids).map{ id in (id, ids.filter{$0==id}.count) }
// You can use map() to turn this into yet another array of dictionaries
let idCountDict = idCounts.map{["itm_id":$0 ,"count":$1]}
print(idCounts) // [(4, 3), (7, 1)]
print(idCountDict) // [["itm_id": 4, "count": 3], ["itm_id": 7, "count": 1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.