Python:计算列表中每对值的值

标签 python list dictionary

我有一个由 key:[list] 组成的字典,其中列表是固定偶数个二进制值,即:

{'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]}

对于每个键,我需要为原始字典中的每个值返回一个新值,这样对于pair(1,1) = 3,pair(0,1) = 2、配对(1,0) = 1,配对(0,0) = 0。

对于上面的示例,输出为:

{'a':[2,1,2],'b':[3,1,0]}

对于 python 和一般编程来说都是新手,并且还没有找到我正在寻找的东西。感谢建议。

最佳答案

首先攻击配对部分:

def paired(binlist, map={(1, 1): 3, (0, 1): 2, (1, 0): 1, (0, 0): 0}):
    return [map[tuple(binlist[i:i + 2])] for i in range(0, len(binlist), 2)]

然后将其应用到您的字典中:

{k: paired(v) for k, v in input_dictionary.iteritems()}

演示:

>>> paired([0,1,1,0,0,1])
[2, 1, 2]
>>> paired([1,1,1,0,0,0])
[3, 1, 0]
>>> input_dictionary = {'a':[0,1,1,0,0,1],'b':[1,1,1,0,0,0]}
>>> {k: paired(v) for k, v in input_dictionary.iteritems()}
{'a': [2, 1, 2], 'b': [3, 1, 0]}

关于Python:计算列表中每对值的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17696893/

相关文章:

arrays - 将范围(有条件)中的唯一值组合到另一个范围中

c# - 如何将 List<X> 转换为 Dictionary<X,Y> 并用 null 填充值?

python - Pandas dataframe.to_html() - 为标题添加背景颜色

html - 垂直列表(从水平返回到默认值)

python - 嵌套 for 循环索引超出范围

html - 如何在宽度 : 100% div? 内放置无序列表(导航菜单)

python - 将嵌套字典转换为Python中的列表?

python - 教程中出现多个 SparkContexts 错误

python - 将未填充的 m/d/y 格式的日期转换为 python pandas 中的日期时间

javascript - Python:setExtreme 后从 Highcharts 读取数据