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

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

总是有另一种方式


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

其他回答

如果列表中没有双重值:

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

要在列表理解中打印一个(指数、值)的<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)]

单线爱好者:

[index for index, datum in enumerate(data) if 'a' in datum]

解释:

>>> data = ['a','ab','bb','ba','alskdhkjl','hkjferht','lal']
>>> data
['a', 'ab', 'bb', 'ba', 'alskdhkjl', 'hkjferht', 'lal']
>>> [index for index, datum in enumerate(data) if 'a' in datum]
[0, 1, 3, 4, 6]
>>> [index for index, datum in enumerate(data) if 'b' in datum]
[1, 2, 3]
>>>

要采取的点:

Python 列表不提供指数; 如果您正在使用,如果您列表列表,它将返回您 ANOTHER 列表 但是该列表将有不同的类型,它将包含每一个和每个元素的指数,如<unk>,我们可以访问<unk>,如变量,分为 comma(,)

谢谢你!请在你的祷告中保持我。

很容易从 0 以外的 1 开始:

for index, item in enumerate(iterable, start=1):
   print index, item  # Used to print in python<3.x
   print(index, item) # Migrate to print() after 3.x+
   

这就足以实现目的:

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