如何访问索引本身以获取如下列表?
ints = [8, 23, 45, 12, 78]
for i in ints:
print('item #{} = {}'.format(???, i))
Run Code Online (Sandbox Code Playgroud)
当我使用循环遍历它时for,如何访问循环索引,在这种情况下从1到5?
我经常花费很多时间在循环中发生处理步骤.以下方法是我如何跟踪处理的位置.在脚本运行时是否有更优雅的Pythonic计算处理数据的方法?
n_items = [x for x in range(0,100)]
counter = 1
for r in n_items:
# Perform some time consuming task...
print "%s of %s items have been processed" % (counter, len(n_items))
counter = counter + 1
Run Code Online (Sandbox Code Playgroud) 我今天早些时候在 Python 中尝试了 for 循环和列表,但我对这可能非常简单的一件事有点困惑......这是我的代码:
animals = ["hamster","cat","monkey","giraffe","dog"]
print("There are",len(animals),"animals in the list")
print("The animals are:",animals)
s1 = str(input("Input a new animal: "))
s2 = str(input("Input a new animal: "))
s3 = str(input("Input a new animal: "))
animals.append(s1)
animals.append(s2)
animals.append(s3)
print("The list now looks like this:",animals)
animals.sort()
print("This is the list in alphabetical order:")
for item in animals:
count = count + 1
print("Animal number",count,"in the list is",item)
Run Code Online (Sandbox Code Playgroud)
无论出于何种原因,计数变量都不起作用,我试图搜索此问题,但找不到任何内容。它说它没有定义,但是如果我输入一个普通数字或一个字符串,它就可以正常工作。(我现在也生病了,所以我无法正常思考,所以这可能很简单,我只是没有抓住它)我是否必须创建一个新的 for 循环?因为当我这样做时:
for item in animal:
for i in range(1,8):
print("Animal …Run Code Online (Sandbox Code Playgroud)