【问题标题】:combine last word in a string with each of the preceding words将字符串中的最后一个单词与前面的每个单词组合起来
【发布时间】:2021-10-30 12:12:16
【问题描述】:

我有一个多行字符串

words = """anticipated, unlikely, preferable, accidental, haphazard result
team members, student, bride    reluctant"""

最后一个单词与倒数第二个单词之间用制表符分隔,而不是逗号

即 "预期的,不太可能的,可取的,偶然的,偶然的\结果"

多行字符串中的每一行都有不同数量的单词

我想从每一行中打印出一个结果,其中最后一个单词与前面的每个单词组合在一起:

anticipated result
unlikely result
preferable result
accidental result
haphazard result
reluctant team members
reluctant students
reluctant bride

抱歉,在尝试了拆分和字典路径后,我无法想出任何代码。

【问题讨论】:

  • 你尝试了什么?似乎是与字典无关的直接拆分

标签: python string split


【解决方案1】:
words = """anticipated, unlikely, preferable, accidental, haphazard\tresult
team members, student, bride\treluctant"""

for line in words.split('\n'):
    word_list_str, last_word = line.split('\t')
    word_list = word_list_str.split(',')
    for word in word_list:
        # use this if the last word should be at the beginning
        print(f'{last_word} {word.strip()}')
        # use this if the last word should be at the end
        print(f'{word.strip()} {last_word}')

【讨论】:

    【解决方案2】:

    您可以通过使用适当的拆分分隔符逐渐隔离部分来在理解中做到这一点:

    words = """anticipated, unlikely, preferable, accidental, haphazard\tresult
    team members, student, bride\treluctant"""
    
    pairings = ( f"{left} {right}"                         # pair up left&right
                 for line in words.split('\n')             # get each line
                 for leftList,right in [line.split('\t')]  # isolate right side
                 for left in leftList.split(', '))         # extract each left side
    
    print(*pairings,sep='\n')
    
    anticipated result
    unlikely result
    preferable result
    accidental result
    haphazard result
    team members reluctant
    student reluctant
    bride reluctant
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多