[英]Find all consecutive letter sequences (character grams) in a word, from length 1 to the length of the word
这有效:
s = 'beach'
lst = []
for c in range(len(s) + 1):
lst.append(list(zip(*[s[i:] for i in range(c)])))
lst2 = [''.join(j) for i in lst for j in i]
print(lst2)
# output
# ['b', 'e', 'a', 'c', 'h', 'be', 'ea', 'ac', 'ch', 'bea', 'eac', 'ach', 'beac', 'each', 'beach']
但是,是否有一种更清洁,更优雅,更Python化的方法来达到相同的结果?
首先:发挥作用。 这样,您就可以强调输入和输出,并且还可以使用默认位置进行解释。
第二:尝试使用暗示变量内容或使用的名称来概述要尝试应用的逻辑。
第三:尝试每行仅执行一个逻辑步骤,或评论您所做的事情。
from itertools import combinations_with_replacement
def parts(word):
""" Returns a list of all substrings of a string"""
combs = combinations_with_replacement(range(len(word)),2)
return [word[x[0]:x[1]+1] for x in combs]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.