【问题标题】:Mapping and looping in pythonpython中的映射和循环
【发布时间】:2015-01-06 23:23:05
【问题描述】:

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

最终结果是

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)

【问题讨论】:

  • 我认为这不是一个好的 stackoverflow 问题。您的问题应该是技术性的和具体的 - 不要帮我编写 X 代码。

标签: python loops dictionary lambda split


【解决方案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 func(sentence): ...
【解决方案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   

【讨论】:

  • 这很好,但应该按照 OP 的要求合并到一个函数中。
【解决方案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)

【讨论】:

  • 我喜欢这个解决方案如何解释长度超过 10 个字符的单词。
【解决方案4】:

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

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

【讨论】:

    【解决方案5】:

    我会构建一个函数来拆分每个单词,然后将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
    

    注意两位数长度单词右侧的长度是如何被一个额外的空格取代的?这是由于我们没有计算长度长度这一事实引起的一个错误,我们只是假设它是一个允许之后的空间。要修复它,我们可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-03
      • 2012-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多