python - 循环中的唯一值数组

标签 python arrays list

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

我有一个由随机数组成的数组。给定值 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]

关于python - 循环中的唯一值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51292589/

相关文章:

下载 zip 文件时的 Python Flask 已损坏

python - 对给定行 pandas 的跨列求和分类特征标签

ios - 如何将数组元素放在表格 View 单元格上

对象列表中的 Python 返回具有类属性集的第一个对象

python - 创建表并从字典中的列表中排序数据

python - 为什么我使用多处理和 pandas 会收到此 KeyError ?

python - django 扩展内置用户模型不允许在管理员中登录

Java-如何通过 GUI 获取数字数组

更改 c 字符串中的一个字符

python - 转换为嵌套在列表列表中的元组列表