【问题标题】:Reset array position in for loop [duplicate]在for循环中重置数组位置[重复]
【发布时间】: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,依此类推。

我不想继续数组索引,我想将它重置为第一个索引。

【问题讨论】:

标签: python arrays for-loop


【解决方案1】:

你的for循环中不需要pass,你也可以使用list compmap

for each in string1:
    pass # not needed
    b.append(ord(each))

使用map

 b = map(ord,string1)

使用列表组合:

[ord(x) for x in string1]

a.index[x] 是无效语法,它是 a.index(x)

但最好使用enumerate获取索引:

c = [b[ind % 23] - ele for ind, ele in enumerate(a)]

【讨论】:

    【解决方案2】:

    您可以使用x % 23x23 之间的划分提醒用作索引:

    print 1 % 23     # 1
    print 22 % 23    # 22
    print 23 % 23    # 0
    

    例如,当x23 的倍数时,a[x % 23] 将返回a 的第一个元素(索引为0 的元素)。

    【讨论】:

    • 谢谢,这解决了我的问题。 ;)
    • 如果您的问题得到解决,请将答案标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2021-12-22
    • 2019-12-05
    • 1970-01-01
    相关资源
    最近更新 更多