Python 3.x 使字符串列表大写-Python 3
我正在学习python,通过一个实际的例子,我遇到了一个似乎找不到解决方案的问题。 下面代码中出现的错误是Python 3.x 使字符串列表大写-Python 3,python-3.x,uppercase,Python 3.x,Uppercase,我正在学习python,通过一个实际的例子,我遇到了一个似乎找不到解决方案的问题。 下面代码中出现的错误是 “list”对象必须具有属性“upper” def to_upper(oldList): newList = [] newList.append(oldList.upper()) words = ['stone', 'cloud', 'dream', 'sky'] words2 = (to_upper(words)) print (words2) 由于upper()方法
“list”对象必须具有属性“upper”
def to_upper(oldList):
newList = []
newList.append(oldList.upper())
words = ['stone', 'cloud', 'dream', 'sky']
words2 = (to_upper(words))
print (words2)
由于upper()
方法仅为字符串定义,而不是为列表定义,因此您应该像下面这样迭代列表和列表中每个字符串的大写字母:
def to_upper(oldList):
newList = []
for element in oldList:
newList.append(element.upper())
return newList
words = ['stone', 'cloud', 'dream', 'sky']
words2 = list(map(str.upper, words))
print (words2)
words = ['stone', 'cloud', 'dream', 'sky']
words2 = [w.upper() for w in words]
print (words2)
这将解决您的代码的问题,但是如果您希望将字符串数组大写,则有更简短/更紧凑的版本
- map函数
。在这种情况下,您的代码如下所示:map(f,iterable)
def to_upper(oldList): newList = [] for element in oldList: newList.append(element.upper()) return newList
words = ['stone', 'cloud', 'dream', 'sky'] words2 = list(map(str.upper, words)) print (words2)
words = ['stone', 'cloud', 'dream', 'sky'] words2 = [w.upper() for w in words] print (words2)
- 列表理解
。在这种情况下,您的代码如下所示:[func(i)for i in iterable]
def to_upper(oldList): newList = [] for element in oldList: newList.append(element.upper()) return newList
words = ['stone', 'cloud', 'dream', 'sky'] words2 = list(map(str.upper, words)) print (words2)
words = ['stone', 'cloud', 'dream', 'sky'] words2 = [w.upper() for w in words] print (words2)
upper()
方法仅对字符串实现。您必须从列表的每个子级调用它,而不是从列表本身调用它。您可以使用列表理解符号,并对单词中的每个字符串应用upper
方法:
words = ['stone', 'cloud', 'dream', 'sky']
words2 = [w.upper() for w in words]
或者使用map
应用该功能:
words2 = list(map(str.upper, words))
很高兴您正在学习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)
其他答案也是正确的,但我希望我的解释有助于您在探索过程中更好地掌握Python。从不同的答案可以看出,有很多方法可以做到这一点。这里还有另一种方法,将to_upper
函数中的最后一行替换为这两行newList.extend([o.upper()表示oldList中的o]);返回新列表