假设我有一个字符串元素列表
wordlist = ["hi what's up home diddle mc doo", "Oh wise master kakarot", "hello have a da"]
并且我希望列表中的每个元素最多包含 3 个单词或 20 个字符。是否有执行此操作的功能?
请您参考如下方法:
两者都可以使用列表理解来完成:
1) 最多 20 个字符:
new_list = [item[:20] for item in wordlist]
>>> new_list
["hi what's up home di", 'Oh wise master kakar', 'hello have a da']
2) 最多 3 个词:
new_list = [' '.join(item.split()[:3]) for item in wordlist if item]
>>> new_list
["hi what's up", 'Oh wise master', 'hello have a']
