![](/img/trans.png)
[英]How do I read a list of numbers in Python, if they are on different lines?
[英]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()
Number of echos: 3
I love mac and cheese
cheese
se
在某种程度上,如果您将原样视为level
或depth
而不是count
,并了解它跟踪您在递归中的深度,它会有所帮助。 好问题 - 我总是在递归退出方面挣扎,这是一个很好的技巧,可以跟踪级别。
此外,如果你的句子很短或分数很小,你可能连一次都不会达到 newlen > 0。 您的代码应该在您的 else 分支中允许这样做并返回"\n".join([b])
。
由于小部分而不必递归:
f= .01 # float(input("Enter the fraction"))
sentence="I love mac and cheese" #input("Enter the sentence")
Number of echos: 1
I love mac and cheese
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.