在开始时为每个循环添加For循环,而不是在循环中仅添加一次

时间:2018-11-24 12:42:52

标签: swift for-loop

我试图将键/值附加到每个数组一次。因此,我的结果应该是数组中每个键/值对的唯一出现。但是,在每次迭代后添加键/值对,然后迭代从头开始重新开始,每次都再次添加键/值对。

如何使每个键/值对仅附加一次?

import UIKit
import PlaygroundSupport

var usernameScoreDict : [String:String] = ["erer":"eree", "veev":"veve", "tbtt":"bttbt", "umum":"muumu", "bvbv":"bbbcb"]

var unArray = [String]()
var hsArray = [String]()

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        usernameScoreDict.forEach { (key,value) in
            print("key is - \(key) and value is - \(value)")
            unArray.append(key)
            hsArray.append(value)
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用如下所示的for循环:-

for (key, val) in usernameScoreDict{
    unArray.append(key)
    hsArray.append(value)
}

之后,您可以使用set删除重复的值(如果有的话)(我认为这样不会发生):-

unArray = (Array(Set(unArray)))
hsArray = (Array(Set(hsArray)))

答案 1 :(得分:0)

您可以直接从字典中创建键和值的数组

import numpy as np
import cv2
from matplotlib import pyplot as plt

MIN_MATCH_COUNT = 10

img1 = cv2.imread('img1.jpg',0)          # queryImage
img2 = cv2.imread('img2.jpg',0) # trainImage

# Initiate SIFT detector
sift = cv2.xfeatures2d.SIFT_create()

# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)

FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)

flann = cv2.FlannBasedMatcher(index_params, search_params)

matches = flann.knnMatch(des1,des2,k=2)

# store all the good matches as per Lowe's ratio test.
good = []
for m,n in matches:
    if m.distance < 0.3*n.distance:
        good.append(m)

if len(good)>MIN_MATCH_COUNT:
    src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
    dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)

    M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0)
    matchesMask = mask.ravel().tolist()

    h,w = img1.shape
    pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)
    dst = cv2.perspectiveTransform(pts,M)

    img2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA)

else:
    print("Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT))
    matchesMask = None

draw_params = dict(matchColor = (0,0,255), # draw matches in green color
                   singlePointColor = None,
                   matchesMask = matchesMask, # draw only inliers
                   flags = 2)

img3 = cv2.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)

#img3 = cv2.resize(img3, None, fx=0.25, fy=0.25)

cv2.imshow("Result", img3)
cv2.waitKey(0)
cv2.destroyAllWindows()