椭圆化列表以Python的形式连接

时间:2014-06-03 17:09:57

标签: python string list join

我几天前了解了列表理解,现在我觉得我对它们有点疯狂,试图让它们解决所有问题。也许我还没有真正理解它们,或者我只是不知道足够的Python来使它们都具有强大的简单。这个问题现在已经占据了我一段时间,我很感激任何意见。

问题

在Python中,将字符串words列表加入到满足以下条件的单个字符串excerpt中:

  • 单个空格分隔元素
  • excerpt的最终长度不超过整数maximum_length
  • 如果words的所有元素都不在excerpt中,请将省略号附加到excerpt
  • words
  • 中只显示excerpt的整个元素

丑陋的解决方案

words = ('Your mother was a hamster and your ' +
         'father smelled of elderberries!').split()
maximum_length = 29
excerpt = ' '.join(words) if len(' '.join(words)) <= maximum_length else \
          ' '.join(words[:max([n for n in range(0, len(words)) if \
                               len(' '.join(words[:n]) + '\u2026') <= \
                               maximum_length])]) + '\u2026'
print(excerpt)      # Your mother was a hamster…
print(len(excerpt)) # 26
是的,有效。 Your mother was a hamster and符合29,但没有留下省略号的余地。但男孩是丑陋的。我可以稍微分解一下:

words = ('Your mother was a hamster and your ' +
         'father smelled of elderberries!').split()
maximum_length = 29
excerpt = ' '.join(words)
if len(excerpt) > maximum_length:
    maximum_words = max([n for n in range(0, len(words)) if \
                         len(' '.join(words[:n]) + '\u2026') <= \
                         maximum_length])
    excerpt = ' '.join(words[:maximum_words]) + '\u2026'
print(excerpt)  # 'Your mother was a hamster…'

但是现在我已经制作了一个我永远不会再使用的变量了。看起来像是浪费。它并没有让任何更漂亮或更容易理解。

有没有更好的方法可以做到这一点我还没见过呢?

3 个答案:

答案 0 :(得分:2)

请参阅我的评论,为什么&#34;简单比复杂&#34;

更好

说,这是一个建议

l = 'Your mother was a hamster and your father smelled of elderberries!'

last_space = l.rfind(' ', 0, 29)

suffix = ""
if last_space < 29:
  suffix = "..."

print l[:last_space]+suffix

这不是你需要的100%,而是很容易扩展

答案 1 :(得分:0)

我的拙见是你在这个清单中是正确的,这个任务不需要理解。我首先得到一个带有拆分的列表中的所有单词,然后可以执行一个while循环,从列表末尾一次删除一个单词,直到len(''。join(list))&lt; maximum_length。

我还要将maximum_length缩短3(elipses的长度),在while循环结束后,将“...”添加为列表的最后一个元素。

答案 2 :(得分:0)

您可以将excerpt修剪为maximum_length。然后,使用rsplit删除最后一个空格并附加到省略号:

def append_ellipsis(words, length=29):
    excerpt = ' '.join(words)[:length]

    # If you are using Python 3.x then you can instead of the line below,
    # pass `maxsplit=1` to `rsplit`. Below is the Python 2.x version.
    return excerpt.rsplit(' ', 1)[0] + '\u2026'

words = ('Your mother was a hamster and your ' +
         'father smelled of elderberries!').split()

result = append_ellipsis(words)
print(result)
print(len(result))