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

xs = [8, 23, 45]

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

所需的产量:

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

总是有另一种方式


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

其他回答

您可以使用指数方法:

ints = [8, 23, 45, 12, 78]
inds = [ints.index(i) for i in ints]

在评论中强调,如果在英寸中有重复,这种方法不会工作,下面的方法应该为英寸中的任何值工作:

ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup[0] for tup in enumerate(ints)]

或替代

ints = [8, 8, 8, 23, 45, 12, 78]
inds = [tup for tup in enumerate(ints)]

如果你想得到指数和值在英寸作为列表的<unk>。

它使用列表方法在这个问题的选择答案,但与列表理解,使它更快的代码较少。

这就足以实现目的:

list1 = [10, 'sumit', 43.21, 'kumar', '43', 'test', 3]
for x in list1:
    print('index:', list1.index(x), 'value:', x)

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

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

首先,指数将从 0 到 4. 编程语言开始从 0 计算; 不要忘记,或者你会遇到一个 index-out-of-bounds 例外。

for x in range(0, 5):

请记住,我写了0到5因为旋转停止一个数字之前的最高。

要获得指数的值,使用

list[index]

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

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