我如何访问指数,同时在一个序列上以一个为旋转的序列?

xs = [8, 23, 45]

for x in xs:
    print("item #{} = {}".format(index, x))

所需的产量:

item #1 = 8
item #2 = 23
item #3 = 45

当前回答

要在列表理解中打印一个(指数、值)的<unk>,使用一个为旋转:

ints = [8, 23, 45, 12, 78]
print [(i,ints[i]) for i in range(len(ints))]

出口:

[(0, 8), (1, 23), (2, 45), (3, 12), (4, 78)]

其他回答

一个简单的答案,使用一段时间的旋转:

arr = [8, 23, 45, 12, 78]
i = 0
while i < len(arr):
    print("Item ", i + 1, " = ", arr[i])
    i += 1

出口:

Item  1  =  8
Item  2  =  23
Item  3  =  45
Item  4  =  12
Item  5  =  78

如果列表中没有双重值:

for i in ints:
    indx = ints.index(i)
    print(i, indx)

您可以使用此代码:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value

使用此代码,如果您需要在路径结束时重新设置指数值:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value
    if index >= len(ints)-1:
        index = 0

您可以使用列表和插入字母中的表达式来获得解决方案。

这是一个简单的方式:

a=[4,5,6,8]
for b, val in enumerate(a):
    print('item #{} = {}'.format(b+1, val))

使用列表以获取与元素的指数,如您引用:

for index, item in enumerate(items):
    print(index, item)

请注意,Python的指数从零开始,所以你会得到0到4与上面的。

count = 0 # in case items is empty and you need it after the loop
for count, item in enumerate(items, start=1):
    print(count, item)

无线控制流

索引 = 0 # Python 的索引从零开始,以便在项目中的项目: # Python 的索引为“每个”卷印(索引,项目)索引 += 1

指数在范围(列(项目)):印刷(指数,项目(项目))

使用列出的功能

for index, item in enumerate(items, start=0):   # default is zero
    print(index, item)

得到一个计算

count = 0 # in case items is empty
for count, item in enumerate(items, start=1):   # default is zero
    print(item)

print('there were {0} items printed'.format(count))


items = ['a', 'b', 'c', 'd', 'e']

enumerate_object = enumerate(items) # the enumerate object

iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)

(0, 'a')

我们可以使用所谓的“序列脱包”来提取这些二重元素:

index, item = iteration
#   0,  'a' = (0, 'a') # essentially this.

>>> print(index)
0
>>> print(item)
a

结论

Python 指数从零开始 若要从一个不可分割的指数中获取这些指数,当您在其上方进行引用时,使用列表函数以异常的方式使用列表(与无包装一起)创建更可读、更可维持的代码:

for index, item in enumerate(items, start=0):   # Python indexes start at zero
    print(index, item)