我如何访问指数,同时在一个序列上以一个为旋转的序列?
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 in xs:
print("item #{} = {}".format(index, x))
所需的产量:
item #1 = 8
item #2 = 23
item #3 = 45
当前回答
根据此讨论:对象列表指数
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。
其他回答
一个具有“对手”变量的圈子设置为一个启动器,这将是一个参数,在格式化行,作为项目号。
当我们通过“i”访问列表时,“i”被格式化为项目价格(或它是什么)。
listos = [8, 23, 45, 12, 78]
counter = 1
for i in listos:
print('Item #{} = {}'.format(counter, i))
counter += 1
出口:
Item #1 = 8
Item #2 = 23
Item #3 = 45
Item #4 = 12
Item #5 = 78
for i in range(len(ints)):
print(i, ints[i]) # print updated to print() in Python 3.x+
您可以使用此代码:
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
如果我要重定数 = [1, 2, 3, 4, 5] 我会
for i, num in enumerate(nums, start=1):
print(i, num)
或得到长度为 l = len(数字)
for i in range(l):
print(i+1, nums[i])
正如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
总是有另一种方式
如前所述,有其他方法来做到这一点,没有在这里解释,他们甚至可能在其他情况下更适用。