【问题标题】:Python 3.3: Split string and create all combinationsPython 3.3:拆分字符串并创建所有组合
【发布时间】:2014-05-19 15:13:00
【问题描述】:

我正在使用 Python 3.3。我有这个字符串:

"Att education is secondary,primary,unknown"

现在我需要拆分最后三个单词(可能有更多或只有一个)并创建所有可能的组合并将其保存到列表中。喜欢这里:

"Att education is secondary"
"Att education is primary"
"Att education is unknown"

最简单的方法是什么?

【问题讨论】:

    标签: python regex list python-3.x


    【解决方案1】:
    data = "Att education is secondary,primary,unknown"
    first, _, last = data.rpartition(" ")
    for item in last.split(","):
        print("{} {}".format(first, item))
    

    输出

    Att education is secondary
    Att education is primary
    Att education is unknown
    

    如果您想要列表中的字符串,则在列表理解中使用相同的字符串,如下所示

    ["{} {}".format(first, item) for item in last.split(",")]
    

    注意:如果逗号分隔值的中间或值本身有空格,这可能不起作用。

    【讨论】:

      【解决方案2】:
      a = "Att education is secondary,primary,unknown"
      last = a.rsplit(maxsplit=1)[-1]
      chopped = a[:-len(last)]
      
      for x in last.split(','):
          print('{}{}'.format(chopped, x))
      

      如果你能保证你的单词用一个空格分隔,这也可以工作(更优雅):

      chopped, last = "Att education is secondary,primary,unknown".rsplit(maxsplit=1)
      for x in last.split(','):
          print('{} {}'.format(chopped, x))
      

      只要最后一个单词的分隔符不包含空格,就可以正常工作。

      输出:

      Att education is secondary
      Att education is primary
      Att education is unknown
      

      【讨论】:

      • 有点低效,你可能想做a.rsplit(" ", 1)
      • 谢谢,您能否解释一下splitrsplit 更好,maxsplit 设置为 1?
      【解决方案3】:
      s="Att education is secondary,primary,unknown".split()
      
      w=s[1]
      l=s[-1].split(',')
      
      for adj in l:
          print(' '.join([s[0],w,s[2],adj]))
      

      【讨论】:

        猜你喜欢
        • 2018-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-29
        • 2016-03-23
        • 1970-01-01
        • 1970-01-01
        • 2022-08-17
        相关资源
        最近更新 更多