繁体   English   中英

在python的循环循环中向后和向前看

[英]Looking backward and forward in a circular loop in python

我想根据用户输入生成单个数字列表。 以循环迭代的方式,列表应包含用户输入,之前的两位数字以及之后的两位数字。 数字的顺序并不重要。

user_input =“1”输出= [9,0,1,2,3]

user_input =“9”输出= [7,8,9,0,1]

使用itertools.cycle我能够获得接下来的两位数,但我找不到可以帮助我获得前两位数的答案。 有没有一种简单的方法来获得前两位数字?

from itertools import cycle
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

user_input = "139"

for i in user_input:    
    s = int(i)
    lst = [s]
    itr = cycle(numbers)
    if s in itr:
        #how can I get the two digits before s?
        lst.append(next(itr))   #getting the next digit
        lst.append(next(itr))

    print(lst)

你可以像这样实现。

def backward_list(n):
    numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    if n == 0 or n == 1:
        x = numbers.index(n) 
    else:
        x = (numbers.index(n)-10)
    return [numbers[x-2],numbers[x-1],numbers[x],numbers[x+1],numbers[x+2]]

执行

In [1]: for i in range(10):
.....:     print backward_list(i)
.....:     
[8, 9, 0, 1, 2]
[9, 0, 1, 2, 3]
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
[4, 5, 6, 7, 8]
[5, 6, 7, 8, 9]
[6, 7, 8, 9, 0]
[7, 8, 9, 0, 1]

可以使用列表理解和% 10

>>> for s in range(10):
        print([i % 10 for i in range(s-2, s+3)])

[8, 9, 0, 1, 2]
[9, 0, 1, 2, 3]
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]
[4, 5, 6, 7, 8]
[5, 6, 7, 8, 9]
[6, 7, 8, 9, 0]
[7, 8, 9, 0, 1]

将iff中的语句修改为:

if s in itr and len(str) == 2:
    lst.append(next(itr))   #getting the next digit
    lst = [s - 1] + lst # prepend the first value
    lst.append(next(itr))
    lst = [s - 2] + lst # prepend the second value

或者你也可以

if s in itr and len(str) == 2:
    lst.append(next(itr))   #getting the next digit
    lst.insert(0, s-1) # prepend the first value
    lst.append(next(itr))
    lst.insert(0, s-2) # prepend the second value

您可以从输入中获取范围并使用该范围来切割numpy数组

编辑:我写代码不好而不测试...感谢@Stefan Pochmann指出...

import numpy as np

def cycle(x):  #x is user input
    indices = np.array(range(x-2, x+3))%10
    numbers = np.array(range(10))
    return numbers[indices]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM