Select 来自带有二进制数的字符串

Select from a string with a binary number

如何使用元组中的二进制文件 select? (在 Python)

例如。 10101,select第一个元素(1)不是第二个(0),select第三个(1),而不是第四个,select第五个和第六个等等。( 101011)

a = 101011
b = 'a','b','c','d','e','f','g'

如何使用 select 'a', 'c', 'e','f' ?

有没有一种干净的方法来做到这一点?最好在 python?

这是演示一种方法的交互式会话

bash-3.2$ python
Python 2.7.12 (default, Nov 29 2016, 14:57:54) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a, b = 101011, ('a','b','c','d','e','f','g')

>>> a, b
(101011, ('a', 'b', 'c', 'd', 'e', 'f', 'g'))

>>> list(str(a))
['1', '0', '1', '0', '1', '1']

>>> zip(list(str(a)),b)
[('1', 'a'), ('0', 'b'), ('1', 'c'), ('0', 'd'), ('1', 'e'), ('1', 'f')]

>>> filter(lambda x:x[0]=='1', zip(list(str(a)),b))
[('1', 'a'), ('1', 'c'), ('1', 'e'), ('1', 'f')]

>>> [x[1] for x in filter(lambda x:x[0]=='1', zip(list(str(a)),b))]
['a', 'c', 'e', 'f']

我们可以使用解构赋值使它更清晰一些

>>> [y for x,y in zip(list(str(a)),b) if x=='1']
['a', 'c', 'e', 'f']
a = 101011
b = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
result = []
temp = list(str(a))
for i in range(len(temp)):
    if temp[i] == '1':
        result.append(b[i])
print(result)

这将处理一般情况。它从 int (num) 中提取位 - 它不期望二进制字符串转换(例如 101010)。

def bin_select(num, mylist):
    idx = 1
    out = []
    while num:
        if (num & 1 != 0):
            out.append(mylist[-idx])
        num = num >> 1
        idx += 1
    return out

if __name__ == "__main__":
    print(bin_select(7, ["a","b","c"]))
    print(bin_select(6, ["a","b","c"]))