[英]concatenate two strings that are in different lists
我需要串聯兩個位於不同列表中的字符串,並檢查輸出字符串是否在字典中。 我嘗試過的代碼是:
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”一詞。
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)
OUTPUT:
{'computer', 'house', 'love', 'president'}
如果預期輸出不應包含第二個列表中的house
,則不要在最終的串聯列表中附加列表y
set(list(map(''.join, list(product(x, y)))) + x) & set(dic)
OUTPUT
{'computer', 'love', 'president'}
使用這種方法,每次在x
嘗試新值時,都需要在y
上重置迭代器。
這樣可能更清楚:
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
,否則移動每個時間上,永不回頭。
對於一個襯板,請使用filter
''.join
並將['']
添加到第二個列表中(因此, if
s則不必做兩個):
list(filter(lambda i: i in dic, [''.join((s1, s2)) for s1 in x for s2 in (y + [''])]))
>>['love', 'president', 'computer']
這對您有用嗎?
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)
這是沒有花哨的簡單版本。 其他人則提出了可能更有效的建議方案。 但是,我認為這種解決方案比某些解決方案(例如,通過檢查串聯的所有變體)更好地捕獲了所需的解決方案。
如果您要進行大量查找,則需要使用集合。
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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.