尝试替换元组列表时出现问题?

时间:2016-12-13 04:33:40

标签: python python-3.x data-structures tuples itertools

我有以下元组列表:

list1 = [('the', 'a'), ('over','1'), ('quick','b'),('fox', 'c'), ('brown', 'd'), ('dog','e'), ('jumps','2')]

我正在尝试更换一些元组,如下所示(*):

('the', 'a') -> ('the', 'ART')
('quick','b') -> ('quick','VERB')
('fox', 'c') -> ('fox', 'ANIMAL')

换句话说,list1的元组应该像这样替换:

list1 = [('the', 'ART'), ('over','1'), ('quick','VERB'),('fox', 'ANIMAL'), ('brown', 'd'), ('dog','e'), ('jumps','2')]

所以,我尝试了以下功能:

def replace_val(alist, key, value):
    return [(k,v) if (k != key) else (key, value) for (k, v) in alist]

问题是我无法通过一个动作从(*)传递所有新元组,我必须这样做:

replace_val(list1, 'the', 'ART')
replace_val(list1, 'quick', 'VERB')
replace_val(list1, 'fox', 'ANIMAL')

因此,我的问题是:如何在一个动作中有效地替换(*)中的所有新元组以获得?:

[('the', 'ART'), ('over','1'), ('quick','VERB'),('fox', 'ANIMAL'), ('brown', 'd'), ('dog','e'), ('jumps','2')]

3 个答案:

答案 0 :(得分:2)

我认为这会有所帮助。

list1 = [('the', 'a'), ('over','1'), ('quick','b'),('fox', 'c'), ('brown', 'd'), ('dog','e'), ('jumps','2')]
list2 = [('the', 'a'), ('over','1'), ('quick','b'),('fox', 'c'), ('brown', 'Dog'), ('dog','e'), ('jumps','2')]
z=(dict(dict(list1),**dict(list2)).items())
print(z)

<强> DEMO

答案 1 :(得分:1)

public ActionResult downloadreport(HttpPostedFileBase file,HttpPostedFileBase file1)
{
    bool missCol = false;
    // .... code to create a excel file (missCol set to true if successful)    
    if (missCol != true)
    {
        TempData["misscol"] = " File download success!";
        return File(newMS, "application/octet-stream", downloadFileName);
    }
    else
    {
        TempData["misscol"] = " Please check your headsource due to missing column!";
        return File(newMS, "application/octet-stream", downloadFileName);
    }    
}

public ActionResult Index()
{
    var msgtemp = Convert.ToString(TempData["misscol"]);
    TempData["errorcode"] = msgtemp;
    return View();
 }

出:

list1 = [('the', 'a'), ('over','1'), ('quick','b'),('fox', 'c'), ('brown', 'd'), ('dog','e'), ('jumps','2')]
dict1 = dict(list1)
print(dict1)
dict1['the'] = 'ART'
dict1['quick'] = 'VERB'
dict1['fox'] = 'ANIMAL'
print(dict1)
list2 = [i for i in dict1.items()]
# or
list2 = list(dict1.items())

print(list2)

答案 2 :(得分:1)

如果你想以简单明了的方式做到这一点,这里有一个:

>>> list1 = [('the', 'a'), ('over','1'), ('quick','b'),('fox', 'c'), ('brown', 'd'), ('dog','e'), ('jumps','2')]
>>> 
>>> list2 = [('the', 'ART'), ('quick', 'VERB'), ('fox', 'ANIMAL')]
>>> 
>>> list3 = []
>>> d1 = dict(list1)
>>> d2 = dict(list2)
>>> 
>>> for k in d1:
        if k not in d2:
            list3.append((k, d1[k]))
        else :
            list3.append((k, d2[k]))


>>> list3
[('jumps', '2'), ('dog', 'e'), ('brown', 'd'), ('the', 'ART'), ('fox', 'ANIMAL'), ('over', '1'), ('quick', 'VERB')]

从元组列表中创建字典将使这两个列表中的查找变得非常快速和简单,然后您只需要获取与您的搜索条件匹配的相应值。