我需要连接两个不同列表中的字符串,并检查输出字符串是否在字典中。我尝试过的代码是:
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”一词。
采用这种方法时,您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
,否则每次运动时间,永不回头。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句