代码之家  ›  专栏  ›  技术社区  ›  vferraz

将列表中的每两项替换为字典中的相应值

  •  0
  • vferraz  · 技术社区  · 7 年前

    我用一个程序将整数向量转换成二进制,现在我需要做反向运算,但我认为我使用的逻辑是不正确的。

    population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]], 
    [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]], 
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]],
    [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]
    
    def BinaryConversion2(population):
        binary_return = []
        binary_index = {(0,0): 0, (0,1): 1, (1,0): 2, (1,1): 3}   
        for game in range (0, len(population)):
            converted = [s for num in population[game][0] for s in binary_index[num]]   
            binary_return.append(converted) 
        return (binary_return)
    

    有人知道如何在字典中引用列表中的每两项各自的值吗?或者在这种情况下可能有用的任何其他东西。

    非常感谢。

    2 回复  |  直到 7 年前
        1
  •  2
  •   saud    7 年前
    for game in population:
        binary_return = [binary_index[(i,j)] for i,j in zip(game[0][0::2], game[0][1::2])]
    
        2
  •  1
  •   jkhadka    7 年前

    这是一个简单可行的解决方案。

    population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]], 
    [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]], 
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]],
    [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]
    binary_index = {(0,0): 0, (0,1): 1, (1,0): 2, (1,1): 3}    
    #zipping
    list2 = []
    for i in [num[0] for num in population]:
        it = iter(i)
        list2.append(zip(it,it))   
    converted = [[binary_index[s] for s in num]for num in list2]   
    

    有了这个,你将得到与填充列表相同的输出形式,但我不知道每个条目中的两个单元素列表是什么,所以我把它删除了。如果你喜欢,你可以编辑它。