我正在尝试使用其他列表在zip list
上进行查找和替换,但出于某种原因,我似乎无法理解这个easy
问题。所以,首先,我有一个拉链列表,看起来像(说myzip_list
):
("this is a united string divided here","this is the value of the string),("this is a multiply string2 united here","this is the value of the string2)....
现在,我有另一个列表,看起来像这样(说replace_list
):
[['united', '##sharp'], ['divided', '##blunt'], ['multiply', '##med']]
我想要做的是将myzip_list
[0]元素替换为double hash
中的replace_list
值。因此,作为最终结果,我想最终得到:
myzip_list = ("this is a ##sharp string ##blunt here","this is the value of the string),("this is a ##med string2 ##sharp here","this is the value of the string2)....
如果有人能指出我正确的方向,我将不胜感激......
修改的
如果replace_list
只包含一个单词,则下面的网络答案确实有效。因此,例如,如果replace_list
看起来像:
[['united all', '##sharp'], ['divided me', '##blunt'], ['multiply all', '##med']]
如果myzip_list
看起来像:
("this is a united all string divided me here","this is the value of the string),("this is a multiply all string2 united all here","this is the value of the string2)....
..然后网络方法失败。
答案 0 :(得分:0)
l = [['united', '##sharp'], ['divided', '##blunt'], ['multiply', '##med']]
d = dict(l)
>>> d
{'multiply': '##med', 'divided': '##blunt', 'united': '##sharp'}
tups = [("this is a united string divided here","this is the value of the string"),("this is a multiply string2 united here","this is the value of the string2")]
[[' '.join([d.get(i,i) for i in sub.split()]) for sub in tup] for tup in tups]
输出
[['this is a ##sharp string ##blunt here', 'this is the value of the string'],
['this is a ##med string2 ##sharp here', 'this is the value of the string2']]
答案 1 :(得分:0)
zip
函数是它自己的逆函数,所以如果你有zip
列表将它自己解压缩!通过像zip(*your_list)
之类的命令,然后使用下面的代码!
import re
myzip_list="(this is a united string divided here,this is the value of the string),(this is a multiply string2 united here,this is the value of the string2)"
tempword=[w for w in re.split('\W', myzip_list) if w]
replace_list=[['united', '##sharp'], ['divided', '##blunt'], ['multiply', '##med']]
my_dict=dict(replace_list)
lst=my_dict.keys()
for i in range(len(tempword)) :
for j in lst:
if tempword[i]==j:
tempword[i]=my_dict[j]
print ' '.join(tempword)
样本:
"this is a ##sharp string ##blunt here this is the value of the string this is a ##med string2 ##sharp here this is the value of the string2"
如果您不想使用re
,请使用re.split('\W', myzip_list)
更改my_ziplist.split()
并删除impoer re
。