我在LeetCode上为zig-zag problem编写了代码。当我使用多行循环时,该功能可以正常工作。但是,当前的print
语句输出一个生成器函数。我尝试使用*
键,但似乎不起作用。
如何解压缩此生成器函数?
我想要的输出是字符串,而不是列表。
谢谢
def zigzag (word, num_rows):
array = []
for _ in range(num_rows):
array.append([])
increasing = 1
array_index = 0
word_index = 0
while word_index < len(word):
if increasing:
array[array_index].append(word[word_index])
array_index +=1
word_index +=1
else:
array[array_index].append(word[word_index])
array_index -=1
word_index +=1
if array_index == -1 and increasing == 0:
increasing = 1
array_index = 1
if array_index == num_rows and increasing == 1:
increasing = 0
array_index = num_rows - 2
return array
if __name__ == "__main__":
word = "PAYPALISHIRING"
num_rows = 4
print ("".join(line) for line in zigzag(word, num_rows))
答案 0 :(得分:1)
单行循环:
print ("".join(line for array in zigzag(word, num_rows) for line in array))
# PINALSIGYAHRPI