Python:为什么itemgetter的返回类型不一致

时间:2018-02-26 12:41:40

标签: python python-3.x

Python id = fopen('probe.dat','r'); t = textscan(id,'%s','delimiter',sprintf('\n')); fclose(id); out = regexp(t{1,1}(6:end-3), '(?<=\()[^)]*(?=\))', 'match', 'all'); probe0 = zeros(size(out,1),3); probe1 = zeros(size(out,1),3); for i = 1:size(out,1) if ~isempty(out{i,:}) probe0(i,:) = (str2double(split(out{i,1}{1,1})))'; probe1(i,:) = (str2double(split(out{i,1}{1,2})))'; else probe0(i,:) = [0,0,0]; probe1(i,:) = [0,0,0]; end end 不会返回长度为0或1的元组。 例如:

itemgetter
  • from operator import itemgetter def get_something(keys): d = { "a": 1, "b": 2, "c": 3 } return itemgetter(*keys)(d) print(type(get_something(["a", "b"]))) # <class 'tuple'> print(type(get_something(["a"]))) # <class 'int'> print(type(get_something([]))) # TypeError: itemgetter expected 1 arguments, got 0 有这么好的理由吗?最后一个itemgetter和最后一个(1,)而不是()

  • 如果我总是想在给定键的情况下返回元组/列表,是否还有其他内置选项?

2 个答案:

答案 0 :(得分:8)

  

如果我总是想要返回一个,还有其他内置选项   给出键的元组/列表?

只需使用理解:

<p>

在上下文中:

[d[k] for k in keys]

答案 1 :(得分:3)

您的部分混淆来自于get_something() func采用单个参数(预期是可迭代的)并在将其传递给itemgetter()时将其解包。这导致get_something()的返回值与其参数不是“symetric”。

如果您定义get_something()代替使用varargs(如itemgetter()那样):

def get_something(*keys):
    d = {
        "a": 1,
        "b": 2,
        "c": 3
    }
    return itemgetter(*keys)(d)

返回值与参数更加一致,即:

# ask for 3 keys, get 3 values:
>>> get_something("a", "b", "c")
(1, 2, 3)

# ask for 2 keys, get 2 values:
>>> get_something("a", "b")
(1, 2)

# ask for one key, get 1 value
>>> get_something("a")
1

# all of this with tuple unpacking in mind:

a, b = get_something("a", "b")
a = get_something("a") 

现在重点是很少有人会因使用itemgetter()来实施您的get_something功能而烦恼 - itemgetter主要用于sorted()get_something的回调像函数/方法(当前行为有意义),def get_something(keys): d = { "a": 1, "b": 2, "c": 3 } return [d[k] for k in keys] 将更典型地用列表表达式实现,即:

public class MarginTopTargetBinding : MvxPropertyInfoTargetBinding
{
    public MarginTopTargetBinding(object target, PropertyInfo targetPropertyInfo) 
        : base(target, targetPropertyInfo)
    {
    }

    protected override void SetValueImpl(object target, object value)
    {
        var view = target as View;
        if (view == null)
            return;

        var marginParams = view.LayoutParameters as ViewGroup.MarginLayoutParams;
        if (marginParams == null)
            throw new InvalidOperationException("You can't set a margin to a View which Layoutparameters are not derived from MarginLayoutParams");

        marginParams.TopMargin = (int)value;

        view.LayoutParameters = marginParams;

        view.RequestLayout();
    }
}

将采用可迭代并返回(可能为空)列表。