连接两个不同列表中的字符串 [英] concatenate two strings that are in different lists
问题描述
我需要连接两个不同列表中的字符串,并检查输出字符串是否在字典中。我尝试过的代码是:
I need to concatenate two strings that are in different lists and check if the output string is in a dictionary. The code I've tried is:
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的字样。
This code is returning only the word that is common to x and y ('Computer'). My desired output is x=[love, president, computer] That is, with the words love and president concatenated in the output.
推荐答案
使用您的方法,您需要在 y
上重置迭代器每次尝试在 x
中使用新值时。
With your approach, you need to reset the iterator over y
each time you try a new value in 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)
y中j的
尝试 y $ c $中的所有事物c>,否则它每次都会移动,并且永远不会回头。
The for j in y
tries all the things in y
, otherwise it moves on each time, and never looks back.
这篇关于连接两个不同列表中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!