【问题标题】:Python 3.x - program repeats way too muchPython 3.x - 程序重复太多
【发布时间】:2013-07-14 02:10:22
【问题描述】:

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

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']

也可以是垂直的,没关系。

【问题讨论】:

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


    【解决方案1】:

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

    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 作为变量名,因为这已经是内置函数的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2023-03-17
      • 1970-01-01
      • 2016-06-29
      • 2016-12-01
      • 2020-03-06
      • 2012-01-31
      相关资源
      最近更新 更多