我必须改变什么周期?

时间:2019-02-07 08:48:17

标签: python for-loop while-loop

我希望将car一词写成hello一词的字母次数。

word = str(input('Enter something to secure: '))    #answer: car
password = str(input('Enter password: '))            #answer: hello   
y = []
for character in word:
    while True:
        i = character
        y.append(i)
        if len(y) == len(password):
            break
    print(y)

我希望将其打印出来

  

['c','a','r','c','a']

不幸的是,它将被打印出来

  

['c','c','c','c','c']

4 个答案:

答案 0 :(得分:4)

使用itertools.cycle

例如:

from itertools import cycle
word = str(input('Enter something to secure: '))    #answer: car
password = str(input('Enter password: '))            #answer: hello   
y = []
word = cycle(word)
for character in password:
    y.append(word.next())
print(y)

y = [word.next() for character in password]

答案 1 :(得分:1)

您应该改为遍历password并逐行打印word字符。您可以使用word

返回到%字符的开头
word = str(input('Enter something to secure: '))
password = str(input('Enter password: '))
y = []
for i in range(len(password)):
    y.append(word[i%len(word)]) # loop through word characters
print(y)

答案 2 :(得分:0)

您应该尝试此操作,而不要使用多个循环。

word = str(input('Enter something to secure: '))    
password = str(input('Enter password: '))            
index = len(word)
output = []
for i in range(0, len(password)):
    output.append(word[i%index])
print(output)

答案 3 :(得分:0)

这是另一种方法,可以减少循环次数并提高性能

word = str(input('Enter something to secure: '))
password = str(input('Enter password: '))
print((word*(len(password)//len(word)+1))[:len(password)])