python 中的映射和循环

Mapping and looping in python

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

最终结果是

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

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

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  
def num_of_chars(sentence):
    words = sentence.split()
    lengths = map(lambda word: len(word), words)
    print sentence+'\n'+''.join([str(l)+' '*(l-len(str(l))+1) for l in lengths])


>>> sentence = 'The quick brown fox jumps the lazy dog'

>>> num_of_chars(sentence)

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

快到了。 ljust 是一个很好用的函数。您只需要编写一个列表理解,它将根据每个长度创建每个对齐的字符串。

例如

sentence = "The quick brown fox jumps the lazy dog"
words = sentence.split()
# this is a list comprension
# you can create a new list by applying functions to each element in the list.
word_lengths = [len(w) for w in words]
word_length_strings = [str(l).ljust(l) for l in word_lengths]
# now you have a list of strings that start with a number and are left padded 
# with spaces to that number.
assert len(words[0]) == len(word_length_strings[0])
# and to join the words up in to one line
line = ' '.join(word_length_strings)
print(sentence)
print(line)

这是一种将句子传递给方法的方法。

def printSentence(inSentence):
    wordList = sentence.split()
    charCount = [len(word) for word in wordList]

    print(str(wordList).replace(']', '').replace('[', '').replace(',', '\t').replace("'", ""))
    print(str(charCount).replace(']', '').replace('[', '').replace(',', '\t').replace("'", ""))

sentence = 'The quick brown fox jumps the lazy dog' 
printSentence(sentence)       

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

我会构建一个函数来拆分每个单词,然后 str.join 一个列表将数字组合在一起。类似于:

def length_mapping(s):
    lengths = map(len, s.split())
    result = "\n".join( [s, "".join([str(length) + ' '*length for length in lengths])] )
    return result

更详细:

def length_mapping_verbose(s):

    words = s.split() # get words from the sentence

    lengths = [] # initialize an empty list to store lengths in
    for word in words:
        lengths.append(len(word))
    # this is exactly:
    # # lengths = [len(word) for word in words]

    length_string = ""
    for length in lengths:
        length_string += str(length)
        length_string += " " * length
        # the number plus an amount of spaces equal to the number.
        # this only works for single-digit word lengths.
        # "supercalifragilisticexpialidocious" will break this! We'll fix it later

    result = s + "\n" + length_string
    return result

正如我之前提到的,很长的词会打破这一点,因为我们会得到这样的结果

some short words with an unimaginably-large word in the middle
4    5     5     4    2  18                  4    2  3   6

请注意两位数长度单词右侧的长度如何被额外的 space 取代?这是一个差一错误,因为我们没有计算长度 的长度 ,我们只是假设这是一个允许 space 之后。要修复它,我们可以这样做:

def length_mapping_safe(s):
    lengths = map(len, s.split())
    result = "\n".join( [s, " ".join([str(length) + " " * (length - len(str(length)) for length in lengths])] )
    return result

也就是说:

" ".join(                           # join with spaces
    [str(length)                    # a list of strings, each starting a length
     + ' ' *                        # plus a number of spaces equal to...
         (length - len(str(length)) # the length minus the number of digits IN that length
    for length in lengths])         # for each length in the string lengths

或者,您可以使用字符串格式来做一些事情,例如:

def length_mapping_with_str_format(s):
    word_formatter = "{{:{}}}"
    words = s.split()
    lengths = [str(len(word)) for word in words]
    lengths_as_words = [word_formatter.format(L).format(L) for L in lengths]
    result = "\n".join([s, " ".join(lengths_as_words)])