2016-12-11 69 views
3
sent = "this is a fun day" 
sent = sent.split() 
newList = [ch for ch in sent] 
print(newList) 
output = ["this" "is","a","fun","day"] 

我要打印的每張發爲好len和每個單詞大寫和輸出應該是如何在列表理解中打印多個值?

output = [["this", 4, 'THIS'], ["is", 2, "IS"], ["a", 1, "A"], ["fun", 3, "FUN"], ["day", 3, "DAY"]] 

回答

3

你的列表中理解應該簡單地生產出三個項目每個迭代的列表:

output = [[word, len(word), word.upper()] for word in sent] 

演示:

>>> sent = "this is a fun day" 
>>> sent = sent.split() 
>>> [[word, len(word), word.upper()] for word in sent] 
[['this', 4, 'THIS'], ['is', 2, 'IS'], ['a', 1, 'A'], ['fun', 3, 'FUN'], ['day', 3, 'DAY']] 
1

您可以在列表理解中使用任何您想要的表達式。在這種情況下,列表:

newList = [[ch, len(ch), ch.upper()] for ch in sent]