是否有一个Python类或模块实现了与BitSet类似的结构?相当于Java的BitSet的Python
22
A
回答
13
标准库中没有任何东西。尝试:
6
看一看这个implementation在Python 3
的实施基本上利用了内置int
类型,这是任意精度的整数类型在Python 3(其中long
是Python 2的等价物)。
#! /usr/bin/env python3
"""
bitset.py
Written by Geremy Condra
Licensed under GPLv3
Released 3 May 2009
This module provides a simple bitset implementation
for Python.
"""
from collections import Sequence
import math
class Bitset(Sequence):
"""A very simple bitset implementation for Python.
Note that, like with normal numbers, the leftmost
index is the MSB, and like normal sequences, that
is 0.
Usage:
>>> b = Bitset(5)
>>> b
Bitset(101)
>>> b[:]
[True, False, True]
>>> b[0] = False
>>> b
Bitset(001)
>>> b << 1
Bitset(010)
>>> b >> 1
Bitset(000)
>>> b & 1
Bitset(001)
>>> b | 2
Bitset(011)
>>> b^6
Bitset(111)
>>> ~b
Bitset(110)
"""
value = 0
length = 0
@classmethod
def from_sequence(cls, seq):
"""Iterates over the sequence to produce a new Bitset.
As in integers, the 0 position represents the LSB.
"""
n = 0
for index, value in enumerate(reversed(seq)):
n += 2**index * bool(int(value))
b = Bitset(n)
return b
def __init__(self, value=0, length=0):
"""Creates a Bitset with the given integer value."""
self.value = value
try: self.length = length or math.floor(math.log(value, 2)) + 1
except Exception: self.length = 0
def __and__(self, other):
b = Bitset(self.value & int(other))
b.length = max((self.length, b.length))
return b
def __or__(self, other):
b = Bitset(self.value | int(other))
b.length = max((self.length, b.length))
return b
def __invert__(self):
b = Bitset(~self.value)
b.length = max((self.length, b.length))
return b
def __xor__(self, value):
b = Bitset(self.value^int(value))
b.length = max((self.length, b.length))
return b
def __lshift__(self, value):
b = Bitset(self.value << int(value))
b.length = max((self.length, b.length))
return b
def __rshift__(self, value):
b = Bitset(self.value >> int(value))
b.length = max((self.length, b.length))
return b
def __eq__(self, other):
try:
return self.value == other.value
except Exception:
return self.value == other
def __int__(self):
return self.value
def __str__(self):
s = ""
for i in self[:]:
s += "1" if i else "0"
return s
def __repr__(self):
return "Bitset(%s)" % str(self)
def __getitem__(self, s):
"""Gets the specified position.
Like normal integers, 0 represents the MSB.
"""
try:
start, stop, step = s.indices(len(self))
results = []
for position in range(start, stop, step):
pos = len(self) - position - 1
results.append(bool(self.value & (1 << pos)))
return results
except:
pos = len(self) - s - 1
return bool(self.value & (1 << pos))
def __setitem__(self, s, value):
"""Sets the specified position/s to value.
Like normal integers, 0 represents the MSB.
"""
try:
start, stop, step = s.indices(len(self))
for position in range(start, stop, step):
pos = len(self) - position - 1
if value: self.value |= (1 << pos)
else: self.value &= ~(1 << pos)
maximum_position = max((start + 1, stop, len(self)))
self.length = maximum_position
except:
pos = len(self) - s - 1
if value: self.value |= (1 << pos)
else: self.value &= ~(1 << pos)
if len(self) < pos: self.length = pos
return self
def __iter__(self):
"""Iterates over the values in the bitset."""
for i in self[:]:
yield i
def __len__(self):
"""Returns the length of the bitset."""
return self.length
4
你可能想看看一个模块我编写的名为bitstring(完整文档here),虽然需要被尽可能快的简单情况我还是建议bitarray。
一些类似的问题:
What is the best way to do Bit Field manipulation in Python?
相关问题
- 1. python相当于java的OutputStream?
- 2. Java:相当于Python的str.format()
- 3. 相当于Java Python的json.dumps
- 4. Python的toordinal()相当于Java?
- 5. Java相当于Python字典
- 6. python相当于java Matcher.quoteReplacement()
- 7. 相当于Java的Class.getResource的Python
- 8. 相当于Java的JNLP Web Start的Python?
- 9. Java的的printStackTrace(),相当于在python
- 10. 相当于python的getattr的Java?
- 11. Python的相当于Java的Set.add()?
- 12. 相当于python的String lstrip()的Java?
- 13. 是否有相当于Java的Boost :: Python?
- 14. java的getByte()在python中相当于
- 15. 相当于Python的Java抽象类吗?
- 16. 相当于Java Python的格式()
- 17. bash相当于Python的os.path.normpath?
- 18. 的Python相当于指针
- 19. 相当于Python的〜/ .bashrc
- 20. 相当于java.io.File的Python
- 21. 的Python相当于在PHP
- 22. Python的枚举相当于
- 23. C#相当于Python的pdb.set_trace()
- 24. Python中的Mahout相当于
- 25. 相当于Python的! operator
- 26. 相当于Python dis()的Lua?
- 27. 相当于C++的Python strtod
- 28. 相当于Python的[:]在c + +
- 29. 相当于C++中的Python
- 30. 的Python相当于猛砸$()
对于非Java程序员,什么是位集合?你想达到什么目的?即使没有等价物存在,也可能有一种很好的pythonic方法来解决你的问题。 – 2010-10-15 23:18:10
基本上,BitSet是一个可以应用于它们的按位操作的位串。该集合还可以通过将位或位集附加到当前位集的末尾来扩展 – 2010-10-16 02:44:24