python中的映射和循环

时间:2015-01-06 23:23:05

标签: python loops dictionary lambda split

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

最终结果是

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)

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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   

答案 2 :(得分:1)

非常接近那里。 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)

答案 3 :(得分:0)

这是一种方法,包括将句子传递给方法。

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

答案 4 :(得分:0)

我构建了一个功能来分割每个单词,然后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

注意两位数字长度右边的长度是如何被一个额外的空间取代的?这是由于我们不计算 的长度 这一事实导致的一个错误,我们只是假设它&# 39; s之后允许空间。为了解决这个问题,我们可以做到:

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