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

xs = [8, 23, 45]

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

所需的产量:

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

当前回答

它可以通过以下代码实现:

xs = [8, 23, 45]
for x, n in zip(xs, range(1, len(xs)+1)):
    print("item #{} = {}".format(n, x))

在这里,范围(1, len(xs)+1);如果您预计输出将从1开始,而不是0,您需要从1开始,并将1添加到估计的总长度,因为Python开始默认地从0索引数字。

Final Output:
item #1 = 8
item #2 = 23
item #3 = 45

其他回答

正如Python的标准一样,有几种方法可以做到这一点。在所有例子中,假设:lst = [1, 2, 3, 4, 5]

使用列表(被认为是最愚蠢的)


for index, element in enumerate(lst):
    # Do the things that need doing here

这也是我认为最安全的选择,因为进入无限回归的机会已经消失了,项目和其指数都保持在变量中,并且没有必要写下任何额外的代码才能访问项目。

创建一个变量以保持指数(使用为)


for index in range(len(lst)):   # or xrange
    # you will have to write extra code to get the element

创建一个变量以保持指数(使用时)


index = 0
while index < len(lst):
    # You will have to write extra code to get the element
    index += 1  # escape infinite recursion

总是有另一种方式


如前所述,有其他方法来做到这一点,没有在这里解释,他们甚至可能在其他情况下更适用。

根据此讨论:对象列表指数

Loop 对抗 iteration

在指标上旋转的当前字符串使用内置范围功能:

for i in range(len(sequence)):
    # Work with index i

超越两个元素和指标可以通过旧的字符或使用新的内置Zip功能实现:

for i in range(len(sequence)):
    e = sequence[i]
    # Work with index i and element e

for i, e in zip(range(len(sequence)), sequence):
    # Work with index i and element e

通过PEP 212 - Loop Counter Iteration。

您可以使用一个变量,例如计算,以计算列表中的元素数量:

ints = [8, 23, 45, 12, 78]
count = 0
for i in ints:
    count = count + 1
    print('item #{} = {}'.format(count, i))

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

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)
for i in range(len(ints)):
   print(i, ints[i]) # print updated to print() in Python 3.x+