gpt4 book ai didi

python - python中的映射和循环

转载 作者:太空宇宙 更新时间:2023-11-04 08:58:39 25 4
gpt4 key购买 nike

我想创建一个显示函数参数(“句子”)的函数,然后在每个单词下方的函数参数中列出每个单词的字符数。这是个人的好奇心而不是实际用途,我不关心自动换行。我不会知道句子中有多少个单词。

最终结果

The quick brown fox jumps the lazy dog
3 5 5 3 5 3 4 3

这是我目前所拥有的...但我不确定如何迭代长度和格式化“长度”之间的间距。最后一行是为实现上述目标而进行的硬编码失败尝试。

sentence = 'The quick brown fox jumps the lazy dog'
words = sentence.split()
#print words


lengths = map(lambda word: len(word), words)
print lengths
print sentence
print str(lengths[0]).ljust(lengths[0]+1) + str(lengths[1]).ljust(lengths[1]+1) + str(lengths[2]).ljust(lengths[2]+1)

最佳答案

>>> def func():
... sentence = "The quick brown fox jumps the lazy dog"
... words = sentence.split()
... print sentence
... for wordlen in map(len, words):
... print wordlen, " "*(wordlen-1-len(str(wordlen))), # the comma terminates the print with a single white space (instead of newline)
...
>>> func()
The quick brown fox jumps the lazy dog
3 5 5 3 5 3 4 3

关于python - python中的映射和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27809001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com