我一直在尝试编写一个简单程序而不导入任何库。我只是想以垂直形式在这个数组中打印以下字符串而不使用任何复杂的算法。如果有人能帮助我,我会很高兴的。 ['旧金山','基督城'悉尼'曼谷'哥本哈根' ]
答案 0 :(得分:0)
这可以使用一些内置函数来完成,例如max()
,len()
和zip()
:
L = ['San Francisco', 'Christchurch ', 'Sydney ', 'Bangkok ', 'Copenhagen ']
max_length = len(max(L, key = lambda x : len(x)))
new_L = []
for e in L:
new_L.append(e + ' ' * (max_length - len(e)))
for e in zip(*new_L):
for el in e:
if el != ' ':
print el,
<强>输出:强>
S C S B C a h y a o n r d n p i n g e F s e k n r t y o h a c k a n h g c u e i r n s c c h o
行:
new_L = []
for e in L:
new_L.append(e + ' ' * (max_length - len(e)))
可以用列表理解来编写,如:
new_L = [e + ' ' * (max_length - len(e)) for e in L]
修改强>
L = ['San Francisco', 'Christchurch ', 'Sydney ', 'Bangkok ', 'Copenhagen ']
# Get the maximum length of a string in the list
max_length = len(max(L, key = lambda x : len(x)))
#print max(L, key = lambda x : len(x)) # get the maximum of the list based in length
#print max_length
# Iterate through indices of max_length: 0, 1, 2, 3 ...
for i in range(max_length):
# Iterate through each city in the list
for city in L:
# If the index is < than the length of the city
if i < len(city) and city[i] != ' ':
print city[i],