【问题标题】:How do I print individual sentences from a Python list of sentences?如何从 Python 句子列表中打印单个句子?
【发布时间】:2020-10-08 01:29:31
【问题描述】:

下面的代码打印列表中的单个字符,而不是打印句子本身。我该如何纠正这个错误?

# Modify this function to return a list of strings as defined above
def list_benefits():
    things = ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"]
    for k in things:
        return k
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
    return "%s is a benefit of functions!" % benefit

def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit in list_of_benefits:
        print(build_sentence(benefit))

name_the_benefits_of_functions()

这是我的输出:

M is a benefit of functions!
o is a benefit of functions!
r is a benefit of functions!
e is a benefit of functions!
  is a benefit of functions!
o is a benefit of functions!
r is a benefit of functions!
g is a benefit of functions!
a is a benefit of functions!
n is a benefit of functions!
i is a benefit of functions!
z is a benefit of functions!
e is a benefit of functions!
d is a benefit of functions!
  is a benefit of functions!
c is a benefit of functions!
o is a benefit of functions!
d is a benefit of functions!
e is a benefit of functions!
>>> 

【问题讨论】:

  • 您的list_benefits() 将只返回列表中的一个(第一个)项目。

标签: python list printing


【解决方案1】:

在这里,您的函数list_benefits() 将返回所有单个句子而不是整个列表,稍后您甚至可以将列表应用于单个句子。然后修改list_benefits()返回整个列表

# Modify this function to return a list of strings as defined above
def list_benefits():
    things = ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"]
    return things
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
    return "%s is a benefit of functions!" % benefit

def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit in list_of_benefits:
        print(build_sentence(benefit))

name_the_benefits_of_functions()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 2014-04-05
    • 2015-10-30
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多