【问题标题】:Cartesian product of a word in python [duplicate]python中单词的笛卡尔积[重复]
【发布时间】:2020-02-19 14:27:47
【问题描述】:

我正在寻找一种方法来获得以下形式的字符串的笛卡尔积,

text = 'school'

我想要这样的结果,

list_ = [(s,c),(c,h),(h,o),(o,o),(o,l)]

这是我尝试过的,

text = 'school'
list_=[]
for i in range(len(text)):
  while i < len(text)+1:
    print(text[i], text[i+1])
    list_.append((text[i], text[i+1]))
    i = i+1

我得到了必要的列表,但还是抛出了一些错误。有什么优雅的方法可以做到这一点?

【问题讨论】:

标签: python python-3.x list cartesian-product


【解决方案1】:
text = 'school'
list(zip(text, text[1:]))

Out[1]:
[('s', 'c'), ('c', 'h'), ('h', 'o'), ('o', 'o'), ('o', 'l')]

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 2016-11-22
    • 2011-09-18
    • 1970-01-01
    • 2019-04-20
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    相关资源
    最近更新 更多