Python,在第n次迭代中打印一次字母n次

时间:2012-04-25 02:53:32

标签: python for-loop while-loop iteration

我似乎对这个感到难过。不幸的是,我甚至不确定如何解释我想要的东西。对于循环中的n次迭代,我想打印一次字母n次。这是一些入门代码......

n = 1
max = 3

letters = string.lowecase
letters.split

while n <= max:
    for letter in letters:
        print letter #n times
    n = n + 1

我想最终:

一 b ... ž AA ... Z Z AAA ... ZZZ

6 个答案:

答案 0 :(得分:4)

字符串可以成倍增加。

>>> 'foo' * 4
'foofoofoofoo'

答案 1 :(得分:4)

for i in range(1, 10):
    for j in "abcdefghijklmnopqrstuvwxyz":
        print j * i

答案 2 :(得分:2)

>>> import string
>>> letters = string.ascii_lowercase

>>> print("".join( x*n for n in range(1,4) for x in letters  ))

abcdefghijklmnopqrstuvwxyzaabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzzaaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz

答案 3 :(得分:1)

使用另一个循环:

# Prints the letters
for letter in letters:
        print letter

# Prints each letter 3 times:
for letter in letters:
    for i in xrange(3):
        print letter

答案 4 :(得分:0)

n = 1
max = 3

letters = string.lowecase
letters.split

while n <= max:
    for letter in letters:
        print letter * n
    n = n + 1

乘法使用字符串

答案 5 :(得分:0)

其他做法

(lambda s: ''.join([x*n for n in xrange(4) for x in s]))(letters)