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

xs = [8, 23, 45]

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

所需的产量:

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

当前回答

你也可以尝试一下:

data = ['itemA.ABC', 'itemB.defg', 'itemC.drug', 'itemD.ashok']
x = []
for (i, item) in enumerate(data):
      a = (i, str(item).split('.'))
      x.append(a)
for index, value in x:
     print(index, value)

产量是

0 ['itemA', 'ABC']
1 ['itemB', 'defg']
2 ['itemC', 'drug']
3 ['itemD', 'ashok']

其他回答

如果列表中没有双重值:

for i in ints:
    indx = ints.index(i)
    print(i, indx)
for i in range(len(ints)):
   print(i, ints[i]) # print updated to print() in Python 3.x+ 

您可以使用范围(len(some_list)) 然后查看此类指数

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

或者使用Python的内置列表功能,允许您在列表上滚动并获取列表中的每个项目的指数和值。

xs = [8, 23, 45]
for idx, val in enumerate(xs, start=1):
    print("item #{} = {}".format(idx, val))

单线爱好者:

[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(,)

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

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

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)