Python使用definine函数打印数组列表和长度

时间:2015-09-30 16:14:32

标签: python

我正在尝试在变量“words”中打印列表并打印每个单词的长度。 我知道如何在不使用def功能时进行打印,但不知道如何使用以下方法进行打印。

words = ["good", "Joy", "computer"]
def list1(words):
    for x in words:
        print x
    return x, len(x)
print list1(words)

这给了我:

good
Joy
Computer
('Computer', 8)

我该怎么做才能打印出来。

good 4
joy 3 
computer 8

由于

3 个答案:

答案 0 :(得分:0)

你需要决定你的函数是应该打印一些东西还是返回一个你打印的字符串。这是后者的一个例子:

words = ["good", "Joy", "computer"]

def list1(words):
    lines = ('{} {}'.format(x, len(x)) for x in words)
    return '\n'.join(lines)

print(list1(words))

如果你喜欢单行,你也可以这样做:

print('\n'.join('{} {}'.format(x, len(x)) for x in words))

答案 1 :(得分:0)

没有返回值的打印示例

words = ["good", "Joy", "computer"]

def list1(words):
    for x in words:
        print ("%s %u"%(x, len(x)))

list1(words)

答案 2 :(得分:0)

您必须让函数以字符串形式返回所有输出,或者在函数内打印所有输出并且不返回任何内容。

  1. 打印函数的返回值:

    function GetWeekOfYear([datetime] $inputDate)
    {
       $day = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetDayOfWeek($inputDate)
       if (($day -ge [System.DayOfWeek]::Monday) -and ($day -le [System.DayOfWeek]::Wednesday))
       {
          $inputDate = $inputDate.AddDays(3)
       }
    
       # Return the week of our adjusted day
       $weekofYear = [System.Globalization.CultureInfo]::InvariantCulture.Calendar.GetWeekOfYear($inputDate, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [System.DayOfWeek]::Monday)
       return $weekofYear
    }
    
  2. 仅在函数内打印:

    words = ["good", "Joy", "computer"]
    
    def list1(words):
        return "\n".join((x, len(x)) for x in words)
    
    print list1(words)