本文整理汇总了Python中operator.methodcaller方法的典型用法代码示例。如果您正苦于以下问题:Python operator.methodcaller方法的具体用法?Python operator.methodcaller怎么用?Python operator.methodcaller使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类operator
的用法示例。
在下文中一共展示了operator.methodcaller方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def __init__(self, apply=None):
"""
:param apply: a tuple, a comma separated string or None
possible values are a combination of:
- x: apply the operation to the sample only
- y: apply the operation to the label only
- train: apply the operation only to the train split
- val: apply the operation only to the val split
- test: apply the operation only to the test split
- all: apply the operation to all
"""
super().__init__()
assert isinstance(apply, (list, tuple, str, type(None)))
if apply == 'all':
self.apply = set()
elif isinstance(apply, (list, tuple)):
self.apply = set(apply)
elif isinstance(apply, str):
self.apply = set(map(operator.methodcaller('strip'), apply.split(",")))
else:
self.apply = set()
# CORRECT:
# self.apply = {'train'}
示例2: _get_classes_from_json
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def _get_classes_from_json(self):
for filename in ("labels.txt", "classes.json"):
path = os.path.join(self.samples_dir, filename)
if not os.path.exists(path):
raise VergeMLError("{} is missing".format(filename))
with open(path) as f:
if filename == "labels.txt":
items = filter(None, map(methodcaller("strip"), f.read().splitlines()))
labels = Labels(items)
else:
self.classes = json.load(f)
files = {}
# prefix the sample with input_dir
for k, v in self.classes['files'].items():
# on windows and linux, separator is /
path = k.split("/")
path.insert(0, self.samples_dir)
fname = os.path.join(*path)
files[fname] = v
self.classes['files'] = files
self.meta['labels'] = labels
示例3: test_difference_incomparable
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def test_difference_incomparable(self, opname):
a = pd.Index([3, pd.Timestamp('2000'), 1])
b = pd.Index([2, pd.Timestamp('1999'), 1])
op = operator.methodcaller(opname, b)
# sort=None, the default
result = op(a)
expected = pd.Index([3, pd.Timestamp('2000'), 2, pd.Timestamp('1999')])
if opname == 'difference':
expected = expected[:2]
tm.assert_index_equal(result, expected)
# sort=False
op = operator.methodcaller(opname, b, sort=False)
result = op(a)
tm.assert_index_equal(result, expected)
示例4: test_set_axis_name_mi
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def test_set_axis_name_mi(self):
df = DataFrame(
np.empty((3, 3)),
index=MultiIndex.from_tuples([("A", x) for x in list('aBc')]),
columns=MultiIndex.from_tuples([('C', x) for x in list('xyz')])
)
level_names = ['L1', 'L2']
funcs = ['_set_axis_name', 'rename_axis']
for func in funcs:
result = methodcaller(func, level_names)(df)
assert result.index.names == level_names
assert result.columns.names == [None, None]
result = methodcaller(func, level_names, axis=1)(df)
assert result.columns.names == ["L1", "L2"]
assert result.index.names == [None, None]
示例5: _AnyMessageToJsonObject
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def _AnyMessageToJsonObject(self, message):
"""Converts Any message according to Proto3 JSON Specification."""
if not message.ListFields():
return {}
# Must print @type first, use OrderedDict instead of {}
js = OrderedDict()
type_url = message.type_url
js['@type'] = type_url
sub_message = _CreateMessageFromTypeUrl(type_url)
sub_message.ParseFromString(message.value)
message_descriptor = sub_message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
js['value'] = self._WrapperMessageToJsonObject(sub_message)
return js
if full_name in _WKTJSONMETHODS:
js['value'] = methodcaller(_WKTJSONMETHODS[full_name][0],
sub_message)(self)
return js
return self._RegularMessageToJsonObject(sub_message, js)
示例6: ConvertMessage
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def ConvertMessage(self, value, message):
"""Convert a JSON object into a message.
Args:
value: A JSON object.
message: A WKT or regular protocol message to record the data.
Raises:
ParseError: In case of convert problems.
"""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value, message)
elif full_name in _WKTJSONMETHODS:
methodcaller(_WKTJSONMETHODS[full_name][1], value, message)(self)
else:
self._ConvertFieldValuePair(value, message)
示例7: _ConvertAnyMessage
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def _ConvertAnyMessage(self, value, message):
"""Convert a JSON representation into Any message."""
if isinstance(value, dict) and not value:
return
try:
type_url = value['@type']
except KeyError:
raise ParseError('@type is missing when parsing any message.')
sub_message = _CreateMessageFromTypeUrl(type_url)
message_descriptor = sub_message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value['value'], sub_message)
elif full_name in _WKTJSONMETHODS:
methodcaller(
_WKTJSONMETHODS[full_name][1], value['value'], sub_message)(self)
else:
del value['@type']
self._ConvertFieldValuePair(value, sub_message)
# Sets Any message
message.value = sub_message.SerializeToString()
message.type_url = type_url
示例8: test_methodcaller
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def test_methodcaller(self):
self.assertRaises(TypeError, operator.methodcaller)
class A:
def foo(self, *args, **kwds):
return args[0] + args[1]
def bar(self, f=42):
return f
a = A()
f = operator.methodcaller('foo')
self.assertRaises(IndexError, f, a)
f = operator.methodcaller('foo', 1, 2)
self.assertEqual(f(a), 3)
self.assertRaises(TypeError, f)
self.assertRaises(TypeError, f, a, 3)
self.assertRaises(TypeError, f, a, spam=3)
f = operator.methodcaller('bar')
self.assertEqual(f(a), 42)
self.assertRaises(TypeError, f, a, a)
f = operator.methodcaller('bar', f=5)
self.assertEqual(f(a), 5)
示例9: test_resample_entirly_nat_window
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def test_resample_entirly_nat_window(self, method, unit):
s = pd.Series([0] * 2 + [np.nan] * 2,
index=pd.date_range('2017', periods=4))
# 0 / 1 by default
result = methodcaller(method)(s.resample("2d"))
expected = pd.Series([0.0, unit],
index=pd.to_datetime(['2017-01-01',
'2017-01-03']))
tm.assert_series_equal(result, expected)
# min_count=0
result = methodcaller(method, min_count=0)(s.resample("2d"))
expected = pd.Series([0.0, unit],
index=pd.to_datetime(['2017-01-01',
'2017-01-03']))
tm.assert_series_equal(result, expected)
# min_count=1
result = methodcaller(method, min_count=1)(s.resample("2d"))
expected = pd.Series([0.0, np.nan],
index=pd.to_datetime(['2017-01-01',
'2017-01-03']))
tm.assert_series_equal(result, expected)
示例10: test_methodcaller
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def test_methodcaller(self):
self.assertRaises(TypeError, operator.methodcaller)
class A:
def foo(self, *args, **kwds):
return args[0] + args[1]
def bar(self, f=42):
return f
a = A()
f = operator.methodcaller('foo')
self.assertRaises(IndexError, f, a)
f = operator.methodcaller('foo', 1, 2)
self.assertEqual(f(a), 3)
f = operator.methodcaller('bar')
self.assertEqual(f(a), 42)
self.assertRaises(TypeError, f, a, a)
f = operator.methodcaller('bar', f=5)
self.assertEqual(f(a), 5)
示例11: find_all_python_versions
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def find_all_python_versions(
self,
major=None, # type: Optional[Union[str, int]]
minor=None, # type: Optional[int]
patch=None, # type: Optional[int]
pre=None, # type: Optional[bool]
dev=None, # type: Optional[bool]
arch=None, # type: Optional[str]
name=None, # type: Optional[str]
):
# type (...) -> List[PathEntry]
version_matcher = operator.methodcaller(
"matches", major, minor, patch, pre, dev, arch, python_name=name
)
pythons = [py for py in self.version_list if version_matcher(py)]
version_sort = operator.attrgetter("version_sort")
return [
c.comes_from for c in sorted(pythons, key=version_sort, reverse=True)
if c.comes_from
]
示例12: test_mapping_with_iterables
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def test_mapping_with_iterables():
input_ = {
'foo': ['bar', 'baz'],
'bar': ['baz', 'foo'],
}
expected = [
"'foo':",
" 0. 'bar'",
" 1. 'baz'",
"'bar':",
" 0. 'baz'",
" 1. 'foo'",
]
actual = list(map(
operator.methodcaller('replace', "u'", "'"),
format_errors(input_),
))
assert set(actual) == set(expected)
示例13: test_mapping_with_mappings
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def test_mapping_with_mappings():
input_ = {
'foo': {
'bar': 'error-a',
'baz': 'error-b',
},
'bar': {
'baz': 'error-c',
'foo': 'error-d',
}
}
expected = [
"'foo':",
" - 'bar': 'error-a'",
" - 'baz': 'error-b'",
"'bar':",
" - 'baz': 'error-c'",
" - 'foo': 'error-d'",
]
actual = list(map(
operator.methodcaller('replace', "u'", "'"),
format_errors(input_),
))
assert set(actual) == set(expected)
示例14: _get_transition
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def _get_transition(self, method, *args, **kwargs):
caller = operator.methodcaller(method, *args, **kwargs)
for template in self._templates:
transition = caller(template)
if transition is not None:
return transition
else:
return caller(self._fallback)
示例15: updateOverlapNow
# 需要导入模块: import operator [as 别名]
# 或者: from operator import methodcaller [as 别名]
def updateOverlapNow(self):
viewport = self.viewport()
distance = viewport.mapToScene(OVERLAP, 0).x() - viewport.mapToScene(0, 0).x()
previous = None
for child in sorted(self.childItems(), key=methodcaller('x')):
if isinstance(child, SequenceKeyframe):
if previous and abs(child.x() - previous.x()) < distance:
child.setOverlapping(True)
previous.setOverlapping(True)
else:
child.setOverlapping(False)
previous = child