Python 从带有二进制数的字符串中选择
如何使用二进制文件从元组中进行选择?(Python语言) 例如,10101,选择第一个元素(1)而不是第二个(0),选择第三个(1),而不是第四个,选择第五个和第六个,等等。。(101011) 如何使用a选择“a”、“c”、“e”和“f”Python 从带有二进制数的字符串中选择,python,string,binary,selection,Python,String,Binary,Selection,如何使用二进制文件从元组中进行选择?(Python语言) 例如,10101,选择第一个元素(1)而不是第二个(0),选择第三个(1),而不是第四个,选择第五个和第六个,等等。。(101011) 如何使用a选择“a”、“c”、“e”和“f” 有没有干净的方法可以做到这一点?最好是用python?这里是一个演示一种方法的交互式会话 bash-3.2$ python Python 2.7.12 (default, Nov 29 2016, 14:57:54) [GCC 4.2.1 Compatibl
有没有干净的方法可以做到这一点?最好是用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']
下面是一个演示一种方法的交互式会话
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']
这将处理一般情况。它从int(num)中提取位-不需要二进制字符串转换(例如101010)
这将处理一般情况。它从int(num)中提取位-不需要二进制字符串转换(例如101010)
欢迎使用Stack Overflow,感谢您的回答!虽然此代码可以按原样工作,但如果您还可以描述您的答案为何有效,以及用户可能以何种方式出错,则可以帮助用户询问更多问题。欢迎使用Stack Overflow,感谢您的回答!虽然此代码可以按原样工作,但如果您还可以描述您的答案为什么有效,以及用户可能以何种方式出错,则它可以帮助用户提出更多问题。
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"]))