在python中,列表中的项目和范围(0,len(x))中的i之间的区别



我正在掌握python中的列表,但是当谈到使用这两个函数的区别时,我感到困惑。

def print_list(x):
    for j in range (0, len(x)):
        print x[j]

def print_list(x):
    for item in list:
        j = 0
        print x[j]
        j++

谁能向初学者解释?谢谢!

我假设

def print_list(x):
    for j in range (0, len(x)):
         print x[j]

是循环在C++中的运行方式。所以你直觉地理解这一点。在这里,range生成(查找生成器)通过len(x) 0的值,for语句遍历它们。

正如评论中指出的那样,您的第二种语法是错误的。我猜你的意思是

def print_list(x):
    for item in x:
        print(item)

for语句循环访问列表x中的每个item
因此,如果您的列表是 [1,3,5,7,9] ,在第一个循环中,item 将具有值1 。在第二个循环中,item的值为 3 。在第 3 个循环中,item的值为 5 。等等。

遍历完所有值后,for循环结束。

第一个例子是正确的,它应该足够pythonic。第二个是不正确的。

def print_list(x):
    for item in list: #where is the iterable oject called list? This shuold be x
        j = 0 # if you use a counter like j you shuold be defining before the loop otherwise you keep resetting it to 0.
        print x[j]
        j++

如果您想在列表中打印所有 elemets 以交互它们,这是一种更 pythonic 和更好的方法。

def print_list(list_item):
    for element in list_item:
         print(element)

你不需要像第一个例子那样使用 range 和 len,list 是可迭代的对象,所以你可以像上面的例子一样做,而无需返回 range()。

最新更新