2017-08-01 69 views
1

我正在学习python和一个实际的例子,我遇到了一个问题,我似乎无法找到解决方案。 我用下面的代码得到的错误是 'list' object has to attribute 'upper'使列表中的字符串大写 - Python 3

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

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

,你可以通过不同的答案告诉有很多方法可以做到这一点。这里只是另一种方法,用'newList.extend(oldList中的o [oper()for o)]来替换'to_upper'函数中的最后一行。 return newList' – davedwards

回答

2

由于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) 
    
0

据我所知,upper()方法的实施仅限字符串。您必须从列表中的每个孩子调用它,而不是从列表本身中调用它。

0

您可以使用列表理解符号和应用upper方法,每个字符串在words

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

或者选择使用map应用功能:

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

真的太好了你正在学习Python!在你的例子中,你正试图大写一个列表。如果你考虑一下,那根本就行不通。您必须大写该列表的元素。此外,如果您在函数结尾处返回结果,则只会从函数获取输出。请参阅下面的代码。

快乐学习!

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!

+0

其他答案也是正确的,但我希望我的解释对你有帮助,以便在探索时更好地掌握Python。 – Crazed