python - 检查Python中的元素是否乱序

标签 python list dictionary

我想检查列表的元素,看看它们与字典相比是否乱序。

我有以下代码:

list = ['jump','double blink']
dictionary = collections.OrderedDict([("wink", 1), ("double blink", 10), 
("close your eyes", 100), ("jump", 1000)])

如果我检查列表的元素,它应该返回False,因为字典中“jump”位于“double眨眼”之后。

起初,我想我可以使用 for 循环来检查列表中操作的索引是否小于字典中下一个操作的索引。

这本质上是将键列表中“jump”的位置(3)与列表中下一个操作的字典中的索引进行比较(下一项是“double眨眼”,它有一个索引1)。因此 4 < 1 将返回 false,但我不确定如何调用 for 循环中的下一项而不出现列表超出范围错误。

最佳答案

您可以使用zip()获取当前项目及其旁边的项目(不涉及索引,因此不用担心 IndexError),然后 all()使用生成器表达式将完成剩下的工作:

>>> lst = ['jump','double blink']
>>> all(dictionary[f] < dictionary[s] for f, s in zip(lst, lst[1:]))
False
>>> lst = d.keys()
>>> all(dictionary[f] < dictionary[s] for f, s in zip(lst, lst[1:]))
True

这里 zip() 返回如下内容:

>>> zip(lst, lst[1:])
[('wink', 'double blink'), ('double blink', 'close your eyes'), ('close your eyes', 'jump')]

另一个选项是使用pairwise recipe from itertools's recipes ,它使用迭代器执行完全相同的操作:

>>> from itertools import tee, izip
>>> def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return izip(a, b)
... 
>>> all(dictionary[f] < dictionary[s] for f, s in pairwise(lst))
True
>>> list(pairwise(lst))
[('wink', 'double blink'), ('double blink', 'close your eyes'), ('close your eyes', 'jump')]

关于python - 检查Python中的元素是否乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27875226/

相关文章:

python - 我如何使用 flask-cache 创建的缓存值

python - 为什么有人会检查 'x in list' ?

python - 列出 Pandas 数据框 - Python

javascript - 数组重排序

python - 用另一个字典中的值替换字典键

python - 有没有一种惯用的 Pandas 方法可以从两个代表开始和停止信号的列表中获取索引

python - resampy之类的包为什么显示 'guvectorize() missing 1 required positional argument: '签名''

python - pyplot 颜色条不显示精确值

C# List of List 的最后一个元素

Python内存管理——字典