簡體   English   中英

如何返回 python 中不同行的列表?

[英]How to return a list on different lines in python?

現在,我的代碼 output 是 ['I love mac and cheese', 'cheese', 'se'],我將如何更改它以使 output 成為一個字符串並出現在不同的行中,所以“我喜歡 mac and cheese (第一行) cheese (第二行) se (第三行). 這是 output 當用戶輸入分數時.369 和 I love mac and cheese for sentence

def echo(a,b, count):
    newlen = int(len(b)*a)
    if newlen > 0:
        count+=1
        return [b] + echo(a,b[-newlen:], count)
    else:
        count+=1
        print("Number of echos: ", count)
        return [b]
        
def main():
    count=0
    f=float(input("Enter the fraction"))
    sentence=input("Enter the sentence")
    print(echo(f,sentence, count))


main()
    

試試下面的。 假設你已經成功實現了正確的句子......

sentence = ["I love mac and cheese", "cheese", "se"]
for item in sentence:
    print(item)
    # If you want a newline character between each item:
    # print("\n") \n is the python syntax for a newline

您可以簡單地將echo function 的返回分配給一個列表,然后遍歷該列表以打印元素。

def main():
    count = 0
    f = float(input("Enter the fraction"))
    sentence = input("Enter the sentence")
    results = echo(f, sentence, count)
    for line in results:
        print(line)

結果是:

Enter the fraction.369
Enter the sentenceI love mac and cheese
Number of echos:  3
I love mac and cheese
 cheese
se

您可以將 echo 方法返回的列表存儲在變量中,並使用 for 循環單獨打印出內容。

results=echo(f,sentence, count)

for result in results:
    print(result)

使用帶有換行符的str.join()方法。

>>> a = ['some text', 'some other text', 'some more']
>>> print(a)
['some text', 'some other text', 'some more']
>>> print('\n'.join(a))
some text
some other text
some more
>>> 


明白了,我想。

因此,關鍵是要了解您何時返回外部世界,即打印。 要觀看的項目是count ,因為在此之前它是 1。

def echo(frac,b, count):
    newlen = int(len(b)*frac)
    if newlen > 0:
        count+=1
        #`count` is going to go up for the inner, recursive, calls
        res = [b] + echo(frac,b[-newlen:], count)

        if count == 1:
            #back to the caller.
            return "\n".join(res)
        else:
            #nope, this a recursive call, leave as list of strings.
            return res
    else:
        count+=1
        print("Number of echos: ", count)
        if count == 1:
            return b
        else:
            return [b]

        
def main():
    count=0
    f= .369 # float(input("Enter the fraction"))
    sentence="I love mac and cheese" #input("Enter the sentence")
    print(echo(f,sentence, count))


main()

output:

Number of echos:  3
I love mac and cheese
 cheese
se

在某種程度上,如果您將原樣視為leveldepth而不是count ,並了解它跟蹤您在遞歸中的深度,它會有所幫助。 好問題 - 我總是在遞歸退出方面掙扎,這是一個很好的技巧,可以跟蹤級別。

此外,如果你的句子很短或分數很小,你可能連一次都不會達到 newlen > 0。 您的代碼應該在您的 else 分支中允許這樣做並返回"\n".join([b])

由於小部分而不必遞歸:

    f= .01 # float(input("Enter the fraction"))
    sentence="I love mac and cheese" #input("Enter the sentence")

output:

Number of echos:  1
I love mac and cheese

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM