【问题标题】:Incrementing both the start and end boundaries of an index in a loop在循环中增加索引的开始和结束边界
【发布时间】:2020-05-15 20:01:03
【问题描述】:

我对 Python 还是很陌生..

我正在尝试生成一个生成连续文本块的 while 循环。这是我尝试过的:

alpha = 'abcdefghijklmnopqrstuvwxyz'

start = 0
i = start
while i < 20:
    for i in range(start, len(alpha)):
        i += 1

        text = alpha[start:i]
        print(text)

        reset = i > 4

        if reset:
            print('reset')
            start += 1
            i = (start)

这个输出:

a
ab
abc
abcd
abcde
reset
bcdef
reset
etc....

但我想要它做的是:

a
ab
abc
abcd
abcde
reset
b
bc
bcd
bcde
bcdef
reset
c
cd
cde
etc...

对我来说,我分配i = start 的位置似乎没有按我想要的方式“工作”?

提前致谢!

【问题讨论】:

  • 为什么要使用while循环?还要考虑 i 的值。
  • 仅供参考:string.ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'

标签: python algorithm loops increment


【解决方案1】:

试试这个:

alpha = 'abcdefghijklmnopqrstuvwxyz'

start = n = 0

while n < len(alpha):
    n += 1

    text = alpha[start:n]
    print(text)

    reset = len(text) > 4

    if reset:
        print('reset')
        start += 1
        n = start

【讨论】:

  • 谢谢!为什么 i
  • 这就是你的问题,我会更新它
  • 实际上你有两个循环的版本是什么?我认为我有一个“for i in range ...”循环嵌套在“while n
  • 其实这两个while循环是完全多余的。答案是相同的,只是答案中的 while 循环包含在 while i &lt; len(alpha): 中。尽管在这种情况下不需要两个循环。如果您想在某个点停止循环(例如if start == len(alpha) - 5: break),如果 n(或 start)达到某个数字,您可以添加一个 break 语句(这将确保您不会在少于要打印五个字符)。上面的两个 while 循环以完全相同的标准退出,因此是多余的。
  • 您的解决方案中的“i”现在是多余的吗?因为您不会在其他任何地方使用它。
【解决方案2】:

这就是我会做的:

alpha = 'abcdefghijklmnopqrstuvwxyz'

for i in range(20):
    for j in range(1,6):
        text = alpha[i:i+j]
        print(text)
    print("reset")

【讨论】:

  • 谢谢,我会试试看。为什么把 j 范围的上边界设为 6?
  • 因为 range(1,6) = [1,2,3,4,5]
【解决方案3】:
alpha = 'abcdefghijklmnopqrstuvwxyz'
count = 0
start = 0
i = 0
while i < 20:
    for j in range(start, len(alpha)):
        count +=1
        text = alpha[start:j]
        print(text)

        reset = count > 5

        if reset:
            print('reset', end='')
            start += 1
            i = start
            count = 0
            break

很确定每个人都已经回答了哈哈,但没有回答所以发布它。

【讨论】:

    猜你喜欢
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 2020-04-12
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多