【问题标题】:Select from a string with a binary number从带有二进制数的字符串中选择
【发布时间】:2017-10-18 19:05:23
【问题描述】:

如何使用二进制从元组中进行选择? (在 Python 中)

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

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

如何使用 a 来选择 'a', 'c', 'e','f' ?

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

【问题讨论】:

    标签: python string binary selection


    【解决方案1】:

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

    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']
    

    【讨论】:

      【解决方案2】:
      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)
      

      【讨论】:

      • 欢迎来到 Stack Overflow,感谢您的回答!虽然此代码可能按原样工作,但如果您还可以描述您的答案为何有效,以及用户可能以何种方式做错了,它可以帮助用户更多地提出问题。
      【解决方案3】:

      这将处理一般情况。它从 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"]))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-17
        • 2015-03-16
        • 1970-01-01
        • 1970-01-01
        • 2016-01-15
        • 1970-01-01
        相关资源
        最近更新 更多