Python 3.x - 程序重复过多

时间:2013-07-14 02:10:23

标签: python list for-loop python-3.x

我正在编写一个打印字符串左列字母的程序。这就是我所拥有的:

str = '''Dear Sam:
From Egypt we went to Italy, and then took a trip to Germany, Holland and England.
We enjoyed it all but Rome and London most.
In Berlin we met Mr. John O. Young of Messrs. Tackico & Co., on his way to Vienna.
His address there is 147 upper Zeiss Street, care of Dr. Quincy W. Long.
Friday the 18th, we join C. N. Dazet, Esquire and Mrs. Dazet, and leave at 6:30 A.M. for Paris
on the 'Q. X.' Express and early on the morning on the 25th of June start for home on <br>the S. S. King.
Very sincerely yours,
Signature of writer'''

splitstr = list(str)
list_a = []
list_b = []

for i in splitstr:
    if i == '\n':
        list_a.append(list_b)
        list_b = []
    else:
        list_b.append(i)

    for i in list_a:
       left_column = list_b[:1]
       print(left_column)
       break

此代码会打印出左列中的字母,但会将其打印出来太多次。输出应该是

['D','F','W','I','H','F','o','V','S']

或者它可以是垂直的,没关系。

1 个答案:

答案 0 :(得分:3)

真的没有必要,为什么不做这样的事情:

text = '''Dear Sam:
From Egypt we went to Italy, and then took a trip to Germany, Holland and England.
We enjoyed it all but Rome and London most.
In Berlin we met Mr. John O. Young of Messrs. Tackico & Co., on his way to Vienna.
His address there is 147 upper Zeiss Street, care of Dr. Quincy W. Long.
Friday the 18th, we join C. N. Dazet, Esquire and Mrs. Dazet, and leave at 6:30 A.M. for Paris
on the 'Q. X.' Express and early on the morning on the 25th of June start for home on the S. S. King.
Very sincerely yours,
Signature of writer
'''

print [line[0] for line in text.splitlines()]
['D', 'F', 'W', 'I', 'H', 'F', 'o', 'V', 'S']

另外,不要使用str作为变量名,因为它已经是内置函数的名称。