简体   繁体   中英

How to print more than one value in a list comprehension?

sent = "this is a fun day"
sent = sent.split()
newList = [ch for ch in sent]
print(newList)
output = ["this" "is","a","fun","day"]

I want to print len of each sent as well and the each word capitalized and output should be

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

Your list comprehension should simply produce a list with three items each iteration:

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

Demo:

>>> 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']]

You can use any expression you want in a list comprehension. In this case, a list:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM