我希望你能帮助我。我有以下问题。

我有一个由随机数组成的数组。给定一个值n,我需要从该数组中选择n个唯一数字,然后对其进行迭代,将下一个元素与先前的n个唯一数字进行比较。
到目前为止,我有这个:

import random
len1=30
array1=[]
for j in range(1,len1):
     z=random.randint(1,30)
     array1.append(z)
n=5
k=0
l=n
for idx,val in enumerate(array1):
     if idx>n-1:
         print(val)
         array2=array1[k:l]
         for p in array2:
             if p == val:
                 #do things
                 ok=1
             else:
                 ok=2
    k=k+1
    l=l+1


总体来说,此例程的行为良好,但是并未考虑array2数的唯一性。我的问题是:如何从array1中提取一个具有唯一n个值的向量?
只有一种条件我不能在向量中看起来“向前”。在循环中,我必须始终使用比实际idx低的array1索引。

换句话说,如果我有n = 5并且:

 array1=[1,2,3,4,5,6,7,7,8,9]


我在idx 8中(即=

 array2=[3,4,5,6,7] (in any order)

最佳答案

一种选择是,循环遍历输入array1,并在输入时用唯一值填充array2。如果您的array2太长,请从列表中删除最旧的项目。

n = 5
arr2 = []
for val in arr1:
    if not arr2:
        arr2.append(val)  # new array case
    else:
        if arr2.count(val):
            arr2.remove(val)  # remove first occurrence (shifts everything ahead of it down one)
            arr2.append(val)  # append val to end
        else:
            arr2.append(val)  # append new unique value
            if len(arr2) > n:
                arr2.pop(0)  # remove oldest value if array is too long
    print(arr2)


在示例arr1 = [1, 2, 3, 4, 5, 6, 5, 4, 7]上运行,我们得到以下输出序列:

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[2, 3, 4, 6, 5]
[2, 3, 6, 5, 4]
[3, 6, 5, 4, 7]

07-24 09:44
查看更多