简体   繁体   English

Python迭代器和可迭代列表

[英]Python iterator and iterable with list

I'm learning Python by watching a Pluralsight course and started to experiment with a iterator and iterable example.我正在通过观看 Pluralsight 课程来学习 Python,并开始尝试使用迭代器和可迭代示例。 One issue I ran into that I can't explain is the following iterator and iterable example:我遇到的一个我无法解释的问题是以下迭代器和可迭代示例:

The following either returns the first item or raises a ValueError if empty:以下要么返回第一项,要么在为空时引发 ValueError:

def first(iterable):
    iterator = iter(iterable)
    try:
        return next(iterator)
    except StopIteration:
        raise ValueError("iterable is empty")

The example in the course worked:课程中的例子有效:

first({"1st","2nd","3rd"})

by returning '1st' but when I changed the content of the list to:通过返回'1st'但是当我将列表的内容更改为:

first({"1","2","3"})

The value returned was '2' instead of '1'返回的值是“2”而不是“1”

Why is this occurring?为什么会出现这种情况?

BTW, I also tried:顺便说一句,我也试过:

first({1,2,3})

and that returns the expected value of: 1并返回预期值: 1

You're not working with list s at all.您根本没有使用list {"1st","2nd","3rd"} is a set literal, and set s are unordered (they iterate in some order, but not a useful order, or even necessarily repeatable order across different runs of Python or set s constructed in different ways within a single run of Python). {"1st","2nd","3rd"}是一个set文字,并且set s 是无序的(它们以某种顺序迭代,但不是一个有用的顺序,甚至在不同的 Python 运行或set s 构造中必须重复的顺序在一次 Python 运行中以不同的方式)。

If you're trying to make a list literal, use [] , not {} .如果您尝试制作list文字,请使用[] ,而不是{} first(["1st","2nd","3rd"]) , first(["1","2","3"]) and first([1,2,3]) will all behave predictably (returning "1st" , "1" and 1 respectively), as list s have ordering. first(["1st","2nd","3rd"]) , first(["1","2","3"])first([1,2,3])行为都可以预测(返回"1st""1"1分别),因为list有顺序。

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

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