2014-08-30 109 views
0

我试图做一个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).... 

..然后Cyber​​s方法失败。

回答

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']] 
+0

问题是我的'''实际上是一个'zip列表'。当我实现你的解决方案时,我得到'AttributeError:'元组'对象没有属性'split'' – JohnJ 2014-08-30 18:32:08

+0

哦好吧我看到了这个问题。编辑我的帖子。 – CoryKramer 2014-08-30 18:36:17

+1

非常感谢你@Cyber​​ - 它完美的工作,我喜欢它,因为它基本上是一个班轮:)接受你的答案。再次感谢 - 为我节省了大量的时间。 – JohnJ 2014-08-30 18:55:10

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) 

DEMO:

"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

+0

不知道我想做'import re' route for this problem .. – JohnJ 2014-08-30 19:29:31

+0

没问题,所以要用'my_ziplist.split()'改变're.split('\ W',myzip_list)''并删除'impoer re'。#我在编辑中添加这个解释! – Kasramvd 2014-08-30 19:40:36

相关问题