如何使用列表推导从列表中返回元组和计数

时间:2016-07-31 20:45:18

标签: python list python-3.x list-comprehension

我有一个函数,使用list comprehension,返回大写的list元素,并计算每个元素。

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()方法但没有成功。我该怎么做呢?

1 个答案:

答案 0 :(得分:4)

您可以使用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]