连接两个位于不同列表中的字符串

时间:2019-03-14 12:54:14

标签: python string list concatenation

我需要连接两个不同列表中的字符串,并检查输出字符串是否在字典中。我尝试过的代码是:

x=['casa','lo','pre','computer']
y=['music','sun','ve','sident','house']
dic=['sunday','love','president','house','computer']
text=[]
errors=[]
iter_y=iter(y)
iter_x=iter(x)

for i in iter_x:
    if i in dic:
        text.append(i)
    else:
        try:
            concatenated= i + next(iter_y)
            if concatenated in dic:
                text.append(concatenated)
      except StopIteration:
          continue
        else:
            errors.append(i)
   print (text)

此代码仅返回x和y共同的单词(“计算机”)。我期望的输出是x = [love,President,computer],即在输出中串联了“ love and President”一词。

5 个答案:

答案 0 :(得分:2)

IIUC,然后您可以使用itertools.product获取两个不同列表的乘积,然后执行设置交集以找到常用词

from itertools import product
x=['casa','lo','pre','computer']
y=['music','sun','ve','sident','house']
dic=['sunday','love','president','house','computer']
set(list(map(''.join, list(product(x, y)))) + x + y) & set(dic)

输出:

{'computer', 'house', 'love', 'president'}

如果预期输出不应包含第二个列表中的house,则不要在最终的串联列表中附加列表y

set(list(map(''.join, list(product(x, y)))) + x) & set(dic)

输出

{'computer', 'love', 'president'}

答案 1 :(得分:0)

采用这种方法,每次在y中尝试新值时,都需要在x上重置迭代器。

这样可能更清楚:

for i in x:
  if i in dic:
    text.append(i)
  else:
    for j in y:
      concatenated = i + j
      if concatenated in dic:
        text.append(concatenated)

for j in y尝试y中的所有事物,否则它每次都会移动,并且永不回头。

答案 2 :(得分:0)

对于一个班轮,请使用filter''.join并将['']添加到第二个列表中(因此您不必执行两个if):

list(filter(lambda i: i in dic, [''.join((s1, s2)) for s1 in x for s2 in (y + [''])]))
>>['love', 'president', 'computer']

答案 3 :(得分:0)

这对您有用吗?

x=['casa','lo','pre','computer']
y=['music','sun','ve','sident','house']
dic=['sunday','love','president','house','computer']

possibles = []
possibles += x
possibles += y # if you want the house...

hits = []
for a in x:
    for b in y:
        possibles.append(a+b)
for a in y:
    for b in x:
        possibles.append(a+b)

for p in possibles:
    if p in dic:
        hits.append(p)

print(p)

答案 4 :(得分:0)

这是一个没有花哨的简单版本。其他人则建议了可能更有效的选择。但是,我认为这种解决方案比某些解决方案(例如,通过检查串联的所有变体)可以更好地捕获所需的解决方案。

如果要进行大量查找,您将希望使用集合。

x = ['casa','lo','pre','computer']
y = ['music','sun','ve','sident','house']
dic = set(['sunday','love','president','house','computer'])
in_dic = set()
for str in y:
    if str in dic:
        in_dic.add(str)
for str1 in x:
    if str1 in dic:
        in_dic.add(str1)
    for str2 in y:
        str3 = str1 + str2
        str4 = str2 + str1
        if str3 in dic:
            in_dic.add(str3)
        if str4 in dic:
            in_dic.add(str4)

print(list(in_dic))
['president', 'love', 'computer', 'house']