2016-03-17 77 views
2

我試圖打印一個字符串,每個字母都有連續數量,所以字符串應該打印「aaabaaccc」。誰能告訴我,我要去哪裏錯了,請爲我只是在Python初學者用連續字母數字打印字符串

h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)] 

g = '' 

for f in h: 

    g = g + f 

回答

0

您試圖解壓您的元組(兩個項目)成一個,你不能這樣做。

試試這個:

for letter, multiplier in h: 
    g += letter * multiplier 
1
h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)] 
g = '' 
for char, count in h: 
    #g = g + f #cant convert tuple to string implicitly 
    g=g+char*count 
print(g) 

String*n字符串重複n次。

1
h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)] 

g = '' 

for i, j in h:  # For taking the tuples into consideration 


    g += i * j 

print(g) # printing outside for loop so you get the final answer (aaabccc) 
3

您可以使用Python列表理解這樣做避免了字符串連接。

print ''.join(letter * count for letter, count in [("a", 3), ("b", 1), ("a", 2), ("c", 3)]) 

這將打印:

aaabaaccc 
0

的Python讓你的數字 「正片疊底」 的字符串:

>>> 'a' * 5 
'aaaaa' 

>>> 'ab' * 3 
'ababab' 

所以,你可以循環在列表上, 「正片疊底」,由弦數字,並以這種方式構建字符串。

>>> h = [("a", 3), ("b", 1), ("a", 2), ("c", 3)] 
>>> g = '' 
>>> for letter, number in h: 
...  g += letter * number 
... 
>>> print(g) 
aaabaaccc 
0

如果 「H」 總是會像被格式化,因爲這一個oneliner是:

g = "".join([i[0]*i[1] for i in h])