将字符串与常用的最后和第一个单词合并

2024-09-30 08:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

以字符串列表形式给出输入

input = [
'mission statement',
'a quick bite to eat',
'a chip off the old block',
'chocolate bar',
'mission impossible',
'a man on a mission',
'block party',
'eat my words',
'bar of soap'
]

我需要写一个函数来组合一对字符串,它们的最后一个和第一个单词是S1+S2

例如: “执行任务的人”—>;S1 “使命宣言”->;S2

然后输出“一个执行任务的人”

上面的字符串列表的输出是

^{pr2}$

这是我用python编写的代码

firstMapper = {}

for val in input:
    wordList = val.split()
    firstMapper[wordList[0]] = ' '.join([str(x) for x in wordList[1:]])

ans = []

for val in input:
    wordList = val.split()
    if wordList[-1] in firstMapper:
        k = val+" "+firstMapper[wordList[-1]]
        if k not in ans:
            ans.append(k)

print(ans)

但这只给了我

['a quick bite to eat my words', 'a chip off the old block party', 'chocolate bar of soap', 'a man on a mission impossible']

我需要在O(n)内完成

更新

我设法这样做了

firstMapper = {}

for val in input:
    wordList = val.split()
    if wordList[0] in firstMapper:
        firstMapper[wordList[0]].append(' '.join(wordList[1:]))
    else:
        temp = []
        temp.append(' '.join(wordList[1:]))
        firstMapper[wordList[0]] = temp

ans = []

for val in input:
    wordList = val.split()
    if wordList[-1] in firstMapper:
        k = list(map(lambda x : val+" "+x, firstMapper[wordList[-1]]))
        if k not in ans:
            ans.extend(k)

print(ans)

这能用更好的方式解决吗?在


Tags: 字符串inforinputifbarvalblock
1条回答
网友
1楼 · 发布于 2024-09-30 08:31:56

下面的代码可以满足您的需要。以下是对功能的描述:

  • 使用collections.defaultdict可以方便地创建字符串到列表的映射
  • 创建所有first words -> list of phrases的映射
  • 创建所有last word -> list of phrases的映射
  • 使用优秀的set类型使这两个映射的键相交,以找出哪一个映射是共同的。在
  • 生成两个列表中单词相同的乘积

它大约是O(n),因为一次传递数据,然后使用了盲目快速的set类型。在

from collections import defaultdict

data = [
  'mission statement',
  'a quick bite to eat',
  'a chip off the old block',
  'chocolate bar',
  'mission impossible',
  'a man on a mission',
  'block party',
  'eat my words',
  'bar of soap'
  ]

last_word_map = defaultdict(list)
first_word_map = defaultdict(list)

for phrase in data:
  words = phrase.split()
  last_word_map[words[-1]].append(' '.join(words[0:-1]))
  first_word_map[words[0]].append(' '.join(words[1:]))

first_word_set = set(first_word_map)
last_word_set = set(last_word_map)

shared_set = set(first_word_map).intersection(last_word_map)

for shared_word in shared_set:
  for last_part in first_word_map[shared_word]:
    for first_part in last_word_map[shared_word]:
      print(first_part + ' ' + shared_word + ' ' + last_part)

输出为:

^{pr2}$

相关问题 更多 >

    热门问题