python - 如果if-statement为true,则扩展并替换

时间:2017-07-20 13:47:28

标签: python

我有一个list tuples我只想创建一个带有if语句的简单嵌套循环,如果它是True它应该替换现有的元组列表。我已经做了这样的事情,它既折旧了元组又反映了旧元组,我无法摆脱旧的元组。

 list_byte = [(1, 1, 0, '0x1636'), (1, 1, 1, '0x19'), (1, 1, 2, '0x02'), (1, 1, 3, '0x2F'), (1, 2, 0, '0x1637')]
result = (2, '0x02', 'LEV'), (2, '0x19', 'RD'), (2, '0x1636', 'IMG'),(2, '0x1637', 'IEM')

 t = []
    for x in list_byte:
        print(x)
        for y in result:
            #print(y)
            if y[:2] == x[2:]:
            #print(y[:2],'-')
                t.extend([x+y[1:]])
        t.append(x)

现在如何打印:

(1, 1, 0, '0x1636', '0x1636', 'IGM')
(1, 1, 0, '0x1636')
(1, 1, 1, '0x19', '0x19', 'RD')
(1, 1, 1, '0x19')
(1, 1, 2, '0x02', '0x02', 'LEV')
(1, 1, 2, '0x02')
(1, 1, 3, '0x2F')
(1, 2, 0, '0x1637', '0x1637', 'IEM')
(1, 2, 0, '0x1637')

我尝试使用else:在if之后然后循环变得疯狂并在一个奇怪的序列中打印每个值...这是我得到的壁橱。

我现在如何打印如何:

(1, 1, 0, '0x1636', '0x1636', 'IGM')
(1, 1, 1, '0x19', '0x19', 'RD')
(1, 1, 2, '0x02', '0x02', 'LEV')
(1, 1, 3, '0x2F')
(1, 2, 0, '0x1637', '0x1637', 'IEM')

4 个答案:

答案 0 :(得分:1)

管理以在经过一些实验后运行此代码。用Python 3.6编写。 (如果您使用的是Python 2.x,只需将print(i)替换为print i

修订代码

list_byte = [(1, 1, 0, '0x1636'), (1, 1, 1, '0x19'), (1, 1, 2, '0x02'), (1, 1, 3, '0x2F'), (1, 2, 0, '0x1637')]
result = (2, '0x02', 'LEV'), (2, '0x19', 'RD'), (2, '0x1636', 'IMG'),(2, '0x1637', 'IEM')

t = []
for x in list_byte:
    line = x
    for y in result:       
        if y[1] == x[3]:
            line = x + y[1:]
    t.append(line)

for i in t: print(i)

控制台输出:

(1, 1, 0, '0x1636', '0x1636', 'IMG')
(1, 1, 1, '0x19', '0x19', 'RD')
(1, 1, 2, '0x02', '0x02', 'LEV')
(1, 1, 3, '0x2F')
(1, 2, 0, '0x1637', '0x1637', 'IEM')

答案 1 :(得分:0)

  

我有一个元组列表,我只想创建一个带有if语句的简单嵌套循环,如果是True,它应该替换列表中现有的元组

以下是您想要的最小示例吗?

mylist = [(1,'a'), (2,'b'), (3,'c')]
print(mylist)
for it in range(len(mylist)):
    if mylist[it][1]=='b':
        mylist[it] = (42, 'foo')
print(mylist)


>> [(1, 'a'), (2, 'b'), (3, 'c')]
>> [(1, 'a'), (42, 'foo'), (3, 'c')]

Try it online!

答案 2 :(得分:0)

您是否尝试过使用filter

像这样:

for i in filter(lambda x: x in [y for y in result if y[:2] == x[2:]] , list_byte):
    print(i)

基本上,如果在符合条件result的{​​{1}}中找到元组,则lambda函数返回true

可能需要进行一些调整以使其正常工作

答案 3 :(得分:0)

list_byte = [(1, 1, 0, '0x1636'), (1, 1, 1, '0x19'), (1, 1, 2, '0x02'),(1, 
1, 3, '0x2F'), (1, 2, 0, '0x1637')]
result = (2, '0x02', 'LEV'), (2, '0x19', 'RD'), (2, '0x1636', 'IMG'),(2, 
'0x1637', 'IEM')
t = []
for x in list_byte:
    for y in result:
        if y[:2] == x[2:]:
            x = x + y[1:]
    t.append(x)

尝试尽可能接近原始代码。希望这有帮助!