简体   繁体   English

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

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

Right now, my codes output is ['I love mac and cheese', ' cheese', 'se'], how would I change it so that the output would be a string and appear on different lines so "I love mac and cheese (first line) cheese (second line) se (third line). This is the output when the user inputs.369 for fraction and I love mac and cheese for sentence现在,我的代码 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()
    

Try the following.试试下面的。 Assuming you have successfully achieved the right sentence...假设你已经成功实现了正确的句子......

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

You can simply assign the return of your echo function to a list, then iterate over that list printing the elements.您可以简单地将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)

Results in:结果是:

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

You can store the list returned by the echo method in a variable and use a for loop to print out the contents separately.您可以将 echo 方法返回的列表存储在变量中,并使用 for 循环单独打印出内容。

results=echo(f,sentence, count)

for result in results:
    print(result)

Use the str.join() method with new-line.使用带有换行符的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
>>> 


Got it, I think.明白了,我想。

So, the key is to is to understand when you are returning back to the outside world, ie to print.因此,关键是要了解您何时返回外部世界,即打印。 The item to watch is count , because it's at 1 right before that.要观看的项目是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: output:

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

In a way, it helps if instead of count you think of as is as level or depth and understand that it tracks how deep in the recursions you are.在某种程度上,如果您将原样视为leveldepth而不是count ,并了解它跟踪您在递归中的深度,它会有所帮助。 Nice question - I always struggle with recursion exits and this is a nice trick to know, tracking levels.好问题 - 我总是在递归退出方面挣扎,这是一个很好的技巧,可以跟踪级别。

Also, if you had a short sentence or a very small fraction, you might not hit newlen > 0 even once.此外,如果你的句子很短或分数很小,你可能连一次都不会达到 newlen > 0。 Your code should allow for that in your else branch and return the "\n".join([b]) .您的代码应该在您的 else 分支中允许这样做并返回"\n".join([b])

without having to recurse because of small fraction:由于小部分而不必递归:

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

output: output:

Number of echos:  1
I love mac and cheese

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM