想想Python第10章练习6

想想Python第10章练习6,python,sorting,python-2.7,python-3.x,Python,Sorting,Python 2.7,Python 3.x,练习: 编写一个名为is_sorted的函数,该函数将列表作为参数,如果列表按升序排序,则返回True,否则返回False。您可以假设(作为先决条件)列表的元素可以与关系运算符进行比较 例如,被排序([1,2,2])应该返回True并且被排序(['b','a'))应该返回False 到目前为止,我已经: def is_sorted(stuff): for i in stuff: if stuff[i+1] > stuff[i]: return True el

练习:

编写一个名为
is_sorted
的函数,该函数将列表作为参数,如果列表按升序排序,则返回
True
,否则返回
False
。您可以假设(作为先决条件)列表的元素可以与关系运算符进行比较

例如,
被排序([1,2,2])
应该
返回True
并且
被排序(['b','a'))
应该
返回False

到目前为止,我已经:

def is_sorted(stuff):
for i in stuff:
    if stuff[i+1] > stuff[i]:
        return True
    else:
        return False
        
numbers = [1, 0, 5, 2, 8]

print is_sorted(numbers)
但每次我更改数字列表时,它似乎都返回True。如何更改此选项以使其正常工作?

for i in stuff:
迭代项,而不是索引。如果您先放入
5
8
,您将得到一个
索引器。另外,如果第一个项目的检查通过,则返回
,太早了!如果有任何异常,您可以
返回False
,但所有异常都必须正常才能
返回True

相反,请尝试使用
enumerate
获取项目和索引:

def is_sorted(stuff):
    for index, item in enumerate(stuff):
        try:
            if item > stuff[index + 1]:
                return False
        except IndexError:
            return True
或者,使用
zip
进行成对比较:

def is_sorted(stuff):
    return all(b >= a for a, b in 
               zip(stuff, stuff[1:]))

for i in stuff
将枚举每个元素。您要做的是枚举元素的索引,因此将循环更改为

适用于范围内的i(len(stuff))

接下来,如果遇到大于当前值的后续元素,则不希望返回True。测试每对相邻元素后,只需返回True,如下所示:

def is_sorted(stuff):    
    for i in range(1,len(stuff)):
        if stuff[i - 1] > stuff[i]:
           return False
    return True

根据@jonrsharpe的答案

这是
itertools
pairwise
配方的一个很好的应用:

from itertools import tee, izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None) #or b.next() on Python 2.5 and below
    return izip(a, b)

def is_sorted(iterable):
    return all(a <= b for a,b in pairwise(iterable))

不幸的是,它对无限生成器没有帮助,例如
已排序(计数(0))

看起来您正在将stuff中的项的
与范围内的i(len(stuff))的
合并

stuff=['a','b','c','d']

  • 使用
    for stuff
    中的项目,您将迭代
    stuff
    中的每个项目:“a”、“b”、“c”和“d”

  • 使用范围内的i的
    (len(stuff))
    ,您将迭代
    stuff的每个索引:0、1、2、3

  • 请注意,变量名
    item
    i
    是这些语句的常见约定,但不是强制性的——您可以用任何需要的内容替换
    item
    i
    。因此,您的第二行代码(
    for i in stuff
    )正在执行上面的#1,而不是您预期的#2


    要让代码执行#2,您必须在第二行代码中使用
    range(len(stuff)
    ,而不仅仅是
    stuff

    ,我知道这是一个旧线程,但我正在尝试完善解决此问题的方法

    我想确保没有任何主体潜入一个整数或一个主要字符串或整数列表中的字符串,例如,['a','b',2]

    我为此编写了一个python程序,但在我看来它有点笨拙。有更好的解决方案吗

    def is_sorted(stuff):
        is_int = 1
        not_int = 0 
    
    if type(stuff[0]) == int:
        of_type = is_int
    else:
        of_type = not_int
    
    for i in range(1,len(stuff)):
        if (of_type == is_int and (type(stuff[i - 1]) == int and type(stuff[i]) == int)) or \
                        (of_type == not_int and (type(stuff[i - 1]) == str and type(stuff[i]) == str)): 
            if stuff[i - 1] > stuff[i]:
                return False
        else:
            print "I saw what you did there!"
            return False
    return True
    
    print is_sorted(['b', 'a']) //False
    print is_sorted(['a', 'b']) //True
    print is_sorted([1, 2]) //True
    print is_sorted(['a', 'b', 2]) //False; "I saw what you did there!"      
    

    我认为您需要进一步确定
    返回True
    def is_sorted(stuff):
        is_int = 1
        not_int = 0 
    
    if type(stuff[0]) == int:
        of_type = is_int
    else:
        of_type = not_int
    
    for i in range(1,len(stuff)):
        if (of_type == is_int and (type(stuff[i - 1]) == int and type(stuff[i]) == int)) or \
                        (of_type == not_int and (type(stuff[i - 1]) == str and type(stuff[i]) == str)): 
            if stuff[i - 1] > stuff[i]:
                return False
        else:
            print "I saw what you did there!"
            return False
    return True
    
    print is_sorted(['b', 'a']) //False
    print is_sorted(['a', 'b']) //True
    print is_sorted([1, 2]) //True
    print is_sorted(['a', 'b', 2]) //False; "I saw what you did there!"