Python:按位排序列表操作 [英] Python: Bitwise-like list operations

查看:34
本文介绍了Python:按位排序列表操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按元素&和元素2个列表由6个二进制数字组成的8个列表,并且工作非常奇怪.c1和c2以长度为8的元组开始,元素为长度为6的元组,而res以c1的列表版本开始.

I'm trying to elementwise & and elementwise | 2 lists of 8 lists of 6 binary digits, and it is working very oddly. c1 and c2 start as tuples of length 8 with elements that are tuples of length 6, and res starts out as a list version of c1.

和:

for x in range(8):
    for y in range(6):
        res[x][y] = (c1[:][x][y])*(c2[:][x][y])

排序:

for x in range(8):
    for y in range(6):
        res[x][y] = int(c1[:][x][y] or c2[:][x][y])

一个例子:

c1:        ((1, 0, 0, 0, 1, 1), (1, 1, 0, 0, 0, 1), (1, 1, 1, 0, 0, 0), (0, 1, 1, 1, 1, 0), (1, 0, 0, 0, 1, 1), (0, 1, 1, 0, 0, 0), (1, 1, 0, 1, 0, 0), (0, 1, 0, 0, 1, 0))
c2:        ((1, 0, 1, 1, 0, 0), (0, 1, 0, 1, 1, 0), (0, 1, 1, 0, 1, 0), (0, 0, 0, 0, 1, 1), (1, 1, 0, 0, 1, 0), (1, 0, 1, 0, 1, 0), (0, 0, 0, 1, 0, 1), (0, 0, 1, 0, 1, 0))
anding res:[[1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0]]
oring res: [[1, 1, 0, 0, 1, 1], [1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1], [1, 1, 0, 0, 1, 1], [1, 1, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0]]

c1和c1的其他输入可能比第一个子列表更复杂.

Other inputs for c1 and can be messed up in much more than the first sublist.

此问题已解决.这很可能是代码其他部分的别名问题,我最终还是使用列表推导.

This has been resolved. It was most likely alias issues in other parts of the code, and I just ended up using list comprehensions.

推荐答案

为什么不简单地使用列表推导来尝试这样的事情:

Why not simply trying something like this using list comprehensions:

c1 = ((1, 0, 0, 0, 1, 1), (1, 1, 0, 0, 0, 1), (1, 1, 1, 0, 0, 0))
c2 = ((1, 0, 1, 1, 0, 0), (0, 1, 0, 1, 1, 0), (0, 1, 1, 0, 1, 0))

print('Bitwise or:  ', [[k | l for k, l in zip(i, j)] for i, j in zip(c1, c2)])
print('Bitwise and: ', [[k & l for k, l in zip(i, j)] for i, j in zip(c1, c2)])

这篇关于Python:按位排序列表操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆