0

我有一个列表列表uarfcnrssi2和一个列表字典band2。然后,我有某些条件将 uarfcnrssi2 中的值添加到 band2,如下所示:

uarfcnrssi2=[[10564, 20, 1],[10637, 26, 1], [10662, 32, 1], [10712, 26, 1], [10837, 15, 1], [10837, 17, 1],
 [2, 10, 13], [3, 18, 13], [44, 12, 13], [10564, 27, 13], [49, 15, 13], [64, 20, 13], [66, 19, 13], [976, 27, 13], [981, 21, 13], [982, 20, 13], [985, 13, 13], [988, 13, 13], [788, 12, 11]]      

band2= {'channel1': 10564, 'channel2': 10589, 'channel3': 10612, 'channel4': 10637,'channel5': 10662, 'channel6': 10687,
'channel7': 10712, 'channel8': 10737, 'channel9': 10762, 'channel10': 10787,'channel11': 10812, 'channel12': 10837, }
var1 = 5
var2 = -190
band2 = {k: [v, v/var1, v/var1+var2] for k, v in band2.iteritems()

代码:

for k, v in band2.items():
    for i in uarfcnrssi2:
        if v[0] == i[0] and i[2] == 1 and len(v)<=3:
            band2[k].append(i[1])

我现在有一本这样的字典:

{'channel11': [10812, 2162, 1972], 'channel10': [10787, 2157, 1967], 'channel3': [10612, 2122, 1932], 'channel2': [10589, 2117, 1927], 'channel1': [10564, 2112, 1922, 20], 'channel7': [10712, 2142, 1952, 26], 'channel6': [10687, 2137, 1947], 'channel5': [10662, 2132, 1942, 32], 'channel4': [10637, 2127, 1937, 26], 'channel9': [10762, 2152, 1962], 'channel8': [10737, 2147, 1957], 'channel12': [10837, 2167, 1977, 15]}   

但是,对于我没有附加第 4 个项目的列表,我想0附加到每个项目的末尾,我没有问题再次循环执行此操作,但是有没有办法编辑我上面的代码来做到这一点?

编辑:我这样做的方式是我想改进的

for k, v in band2.items():
    for i in uarfcnrssi2:
        if v[0] == i[0] and i[2] == 1 and len(v)<=3:
            band2[k].append(i[1])

for k, v in band2.items():
    if len(v) <=3:
        band2[k].append(0)
print band2  

最终输出:

band2 = {'channel11': [10812, 2162, 1972, 0], 'channel10': [10787, 2157, 1967, 0], 'channel3': [10612, 2122, 1932, 0], 'channel2': [10589, 2117, 1927, 0], 'channel1': [10564, 2112, 1922, 20], 'channel7': [10712, 2142, 1952, 26], 'channel6': [10687, 2137, 1947, 0], 'channel5': [10662, 2132, 1942, 32], 'channel4': [10637, 2127, 1937, 26], 'channel9': [10762, 2152, 1962, 0], 'channel8': [10737, 2147, 1957, 0], 'channel12': [10837, 2167, 1977, 15]}
4

1 回答 1

0

OK I understand the issue now. I think you can combine your two loops, like this:

for v in band2.values():
    for i1, i2, i3 in uarfcnrssi2:
        if v[0] == i0 and i2 == 1 and len(v) <= 3:
            v.append(i1)
    if len(v) <= 3: # never matched any list values, so add zero instead
        v.append(0)

Note that the outer loop is over the values of the dictionary, since you were only using the key for indexing (which isn't necessary, since you already have a reference to the value). I've also made the inner loop unpack the three values into individual variables. I suggest giving them meaningful names (I've only used i0, i1 and i2 because I don't know what the values mean).

于 2013-04-24T10:08:42.553 回答