如何使用二进制文件从元组中进行选择? (在Python中)
EG。 10101,选择第一个元素(1)而不是第二个(0),选择第三个(1),而不是第四个,选择第五个和第六个等。(101011)
a = 101011
b = 'a','b','c','d','e','f','g'
如何使用a来选择'' c',' e' f' f' ?
有一个干净的方法吗?最好是在python?
答案 0 :(得分:0)
这是一个展示一种方法的互动会议
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']
答案 1 :(得分:0)
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)
答案 2 :(得分:0)
这将处理一般情况。它从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"]))