【问题标题】:Make Strings In List Uppercase - Python 3使列表中的字符串大写 - Python 3
【发布时间】:2018-01-08 22:14:32
【问题描述】:

我正在学习 python,并通过一个实际示例遇到了一个我似乎无法找到解决方案的问题。 我使用以下代码得到的错误是 'list' object has to attribute 'upper'

def to_upper(oldList):
    newList = []
    newList.append(oldList.upper())

words = ['stone', 'cloud', 'dream', 'sky']
words2 = (to_upper(words))
print (words2)

【问题讨论】:

  • 从不同的答案可以看出,有很多方法可以做到这一点。这是另一种方式,将to_upper 函数中的最后一行替换为这两行newList.extend([o.upper() for o in oldList]); return newList

标签: python-3.x uppercase


【解决方案1】:

由于upper() 方法仅用于字符串而非列表,您应该像这样遍历列表并将列表中的每个字符串大写:

def to_upper(oldList):
    newList = []
    for element in oldList:
        newList.append(element.upper())
    return newList

这将解决您的代码问题,但是如果您想将字符串数组大写,还有更短/更紧凑的版本。

  • 地图函数map(f, iterable)。在这种情况下,您的代码将如下所示:

    words = ['stone', 'cloud', 'dream', 'sky']
    words2 = list(map(str.upper, words))
    print (words2)
    
  • 列表理解 [func(i) for i in iterable]。在这种情况下,您的代码将如下所示:

    words = ['stone', 'cloud', 'dream', 'sky']
    words2 = [w.upper() for w in words]
    print (words2)
    

【讨论】:

    【解决方案2】:

    很高兴您正在学习 Python!在您的示例中,您正在尝试将列表大写。如果你仔细想想,那根本行不通。您必须将该列表的 elements 大写。此外,如果您在函数末尾返回结果,您只会从函数中获得输出。请参阅下面的代码。

    学习愉快!

     def to_upper(oldList):
            newList = []
            for l in oldList:
              newList.append(l.upper())
            return newList
    
        words = ['stone', 'cloud', 'dream', 'sky']
        words2 = (to_upper(words))
        print (words2)
    

    Try it here!

    【讨论】:

    • 其他答案也是正确的,但我希望我的解释对您在探索时更好地掌握 Python 有所帮助。
    【解决方案3】:

    您可以使用 list comprehension 表示法并将upper 方法应用于words 中的每个字符串:

    words = ['stone', 'cloud', 'dream', 'sky']
    words2 = [w.upper() for w in words]
    

    或者使用map 来应用函数:

    words2 = list(map(str.upper, words))
    

    【讨论】:

      【解决方案4】:

      AFAIK,upper() 方法仅适用于字符串。您必须从列表的每个子项中调用它,而不是从列表本身中调用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-06
        • 1970-01-01
        • 1970-01-01
        • 2017-10-22
        • 2011-08-31
        • 1970-01-01
        相关资源
        最近更新 更多