繁体   English   中英

断言列表中的所有项目都满足 Python 中的条件

[英]Assert that all the items in a list satisfy a condition in Python

我需要你的帮助。 我正在编写一个代码来将两个排序的 arrays 合并到一个排序数组中。 问题是我不知道如何为输入设置条件。

def merge_and_sort (A,B):
    # condition that A and B are already sorted
   necessary step
   return result

例如,A=[1, 2, 4, 10, 20] 和 B=[2, 4, 4.5, 10, 100] 是可以接受的; 但 A=[1, 2, 4, 10, 20] 和 B=[2, 4, 4.5, 100, 10] 不会。

提前致谢。

检查列表中的数字是否小于下一个数字。

代码:

def is_sorted(L):
    return all([ L[i] <= L[i+1] for i in range(len(L)-1)])
    
A=[1, 2, 4, 10, 20] 
B=[2, 4, 4.5, 100, 10]
B1=[2, 4, 4.5, 10, 100]

print('A is', ('not sorted', 'sorted')[is_sorted(A)])
print('B is', ('not sorted', 'sorted')[is_sorted(B)])
print('B1 is', ('not sorted', 'sorted')[is_sorted(B1)])
print('A and B are', ('not sorted', 'already sorted')[is_sorted(A) and is_sorted(B)])
print('A and B1 are', ('not sorted', 'already sorted')[is_sorted(A) and is_sorted(B1)])

Output:

A is sorted
B is not sorted
B1 is sorted
A and B are not sorted
A and B1 are already sorted
def merge_and_sort (A,B):
    # maiking a varibale to check if both list are sorted
    both_sorted = False
    
    # comparing a orignal listed with a sorted on to check if 
    # its already sorted or not 
    
    if A == sorted(A) and B == sorted(B):
        both_sorted = True

    #This list will contain both the list
    result  = []
    
    #if both lists are sorted put list A in result
    # and then list B
    if both_sorted == True:
        print("Both list accepted")
        for i in A:
            result.append(i)
        for i in B:
            result.append(i) 

        result.sort()


    
    
    else:
        print("Lists are not sorted")           
    return result


A = [1, 2, 4, 10, 20] 
B = [2, 4, 4.5, 10, 100] 

res = merge_and_sort(A,B)
print(res)

暂无
暂无

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

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