【发布时间】:2014-10-15 00:23:16
【问题描述】:
我想在 python 的 For 循环中达到其最后一个索引后重置数组索引位置。
示例:
# Array 1
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
# string
string1 = "hello world here i am bla bla bla bla bla"
b = []
# --------------------------------------------------------------------
# Here I'm adding to a new array the odd of each letter in the string:
for each in string1:
pass
b.append(ord(each))
# --------------------------------------------------------------------
# Now I'm trying to subtract to each odd the number in the `b` array,
# the value of the number in the same position of the `a` array.
c = []
x = 0
for number in b:
pass
c.append(b.index[x] - a.index[x])
x = x + 1
这里的问题是我会收到一个indexError 说'a' list is out of range。
追加是因为 a 列表有 23 个对象,而 b 列表有 41 个。 如何在到达最后一项时将 a 索引计数重置为 0,因此第 24 个字母将再次为 1,第 25 个字母为 2,依此类推。
我不想继续数组索引,我想将它重置为第一个索引。
【问题讨论】:
-
抱歉,我注意到我的帖子没有以最佳方式格式化。希望你能理解。
-
b.index[x]语法无效 -
使用来自itertools的cycle() docs.python.org/2/library/itertools.html