繁体   English   中英

如何对 N 个元素的列表进行排序,然后用 -1 替换 0 到 N 之间的缺失值

[英]How to sort a list of N elements and then replace missing values between 0 to N with -1

示例测试用例

                     Input                                  Output

 - Test Case 1       3 1 4 2 5 0                            0 1 2 3 4 5
 - Test Case 2       4 7 -1 9 -1 5 3 -1 -1 -1           -1 -1 -1 3 4 5 -1 7 -1 9

你可以看到缺失的数字在它们缺失的地方被 -1 替换(即以排序的方式)我怎样才能实现这个输出,我能够通过

num = list(set((map(int, input().split()))))
num.sort()

您可以将输入列表中的数字存储在set 中 然后要获取输出列表,您可以遍历数字范围并检查它们是否在集合中:

in_list = [4, 7, -1, 9, -1, 5, 3, -1, -1, -1]    
s = set(in_list)
out_list = [i if i in s else -1 for i in range(len(in_list))]    
print(out_list)  # [-1, -1, -1, 3, 4, 5, -1, 7, -1, 9]
def sort(list):
    length = len(list) - 1
    unsorted = True

    while unsorted:
        for element in range(0,length):
            unsorted = False
            if list[element] > list[element + 1]:
                hold = list[element + 1]
                list[element + 1] = badList[element]
                list[element] = hold
            else:
                unsorted = True
    i = 0
    while i < range(len(list)-1):
        if list[i+1] - list[i] != 1 and list[i+1] != -1 and list[i] != -1:
            list.insert(i+1, -1)
            i = i - 1
        i = i - 1
    return list
list = [3,1,4,2,5,0]
print(sort(list))

这是你追求的吗?

Python 列表理解是一个非常简单的概念。 您可以遍历列表并根据您的条件获取列表的元素。

考虑以下示例:

old_list = [1, 2, 3, 4, 5]
new_list = []
for elem in old_list:
    new_list.append(elem)
print(new_list)  # [1, 2, 3, 4, 5]

该代码基本上是从另一个创建列表。 这里没什么好看的。 但这不是pythonic方法。 让我们用pythonic方式来做:

old_list = [1, 2, 3, 4, 5]
new_list = [elem for elem in old_list]

这完全相同。 但是为什么我们不直接将old_list复制到new_list呢? 因为列表理解不仅仅可以用于复制元素。 看到这个:

old_list = [1, 2, 3, 4, 5]
new_list = [elem+1 for elem in old_list]
print(new_list)  # [2, 3, 4, 5, 6]

现在您创建了一个不同的列表! 您可以对列表元素进行任何操作来创建一个新元素。

由于python也有三元运算,因此也可以这样做:

a = 3 if x>2 else 4

这段代码的缩写:

if x>2:
    a = 3
else:
    a = 4

当您将列表推导式和三元运算结合起来时,只需 1 行代码即可解决您的问题。

a = [1, 2 ,3 ,4 ,5]
def zerofy(arr, n):
    return [-1 if 0<=elem<=n else elem for elem in arr]

zerofy(a, 2)
# [-1, -1, 3, 4, 5]

这就是我的做法(如果我正确理解了您的问题)

test1 = [3, 1, 4, 2, 5, 0]
test2 = [4, 7, -1, 9, -1, 5, 3, -1, -1, -1]

print([i if i in test1 else -1 for i in range(0, len(test1))])
print([i if i in test2 else -1 for i in range(0, len(test2))])

>>>[0, 1, 2, 3, 4, 5]
>>>[-1, -1, -1, 3, 4, 5, -1, 7, -1, 9]

纯 Python 方法将涉及列表推导式、 rangeset 如果您对较大数组的性能感兴趣,我建议使用 NumPy 等 3rd 方库:

import numpy as np

a = np.array([3, 1, 4, 2, 5, 0])
b = np.array([4, 7, -1, 9, -1, 5, 3, -1, -1, -1])

def reindexer(x):
    res = np.arange(len(x) + 1)
    res[~np.isin(res, x)] = -1
    return res

reindexer(a)  # array([0, 1, 2, 3, 4, 5])
reindexer(b)  # array([-1, -1, -1,  3,  4,  5, -1,  7, -1,  9])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM