省略列表连接,Pythonically

2024-05-17 19:44:38 发布

您现在位置:Python中文网/ 问答频道 /正文

几天前我学习了列表理解法,现在我想我对它们有点疯狂了,想让它们解决所有的问题。也许我还没有真正理解它们,或者我只是还不了解足够的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…'

但现在我已经做了一个变量,我再也不用它了。好像是浪费。它并没有让任何东西变得更漂亮或更容易理解。你知道吗

有没有比这更好的方法我还没见过呢?你知道吗


Tags: and元素yourleniflengthwordsprint
3条回答

请看我关于“简单胜于复杂”的评论

也就是说,这里有一个建议

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%,而是很容易扩展

您可以将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))

我的拙见是,你在这张单子上说得对,理解对于这项任务是不必要的。我会首先使用拆分得到列表中的所有单词,然后执行while循环,从列表末尾一次删除一个单词,直到len('''.join(list))<;最大长度。你知道吗

我还将把最大\u长度缩短3(省略号的长度),在while循环结束后,添加“…”作为列表的最后一个元素。你知道吗

相关问题 更多 >