我有一个函数,它使用列表推导以大写形式返回列表元素,并对每个元素进行计数。
def wordlengths(mywords):
upperword = [word.upper() for word in mywords]
lenword = [len(i) for i in mywords]
return upperword, lenword
print(wordlengths(["The", "quick", "brown", "fox"]))
返回:
(['THE', 'QUICK', 'BROWN', 'FOX'], [3, 5, 5, 3])
但我需要它返回这样的成对元组:
[("THE", 3), ("QUICK", 5), ("BROWN", 5), ("FOX", 3)]
我尝试使用
zip()
方法没有成功。我该怎么做呢? 最佳答案
您可以使用zip()
:
def wordlengths(mywords):
upperword = [word.upper() for word in mywords]
lenword = [len(i) for i in mywords]
return list(zip(upperword, lenword))
但是,为什么不一次构造列表:
def wordlengths(mywords):
return [(word.upper(), len(word)) for word in mywords]