与输入参数一样多的元组?

时间:2019-08-31 01:03:59

标签: python tuples

是否可以不创建任何中间列表或将其设置为具有将整数作为输入的函数,然后创建具有与输入整数一样多的元组的函数。

def create_none_tuple(x):
# say if x = 3 then function should return (None,None,None)
    pass

3 个答案:

答案 0 :(得分:2)

可以通过将tuple乘以int

def create_none_tuple(x):
  return (None,) * x

print(create_none_tuple(3))

输出:

(None, None, None)

但是,对于除基本类型以外的任何其他内容,都可能导致错误,例如:

def create_list_tuple(x):
  return ([],) * x

lt = create_list_tuple(3)
print(lt)        #  =>  ([], [], [])
lt[0].append(1)  #  modifying one of them is modifying all of them
print(lt)        #  =>  ([1], [1], [1])

在这种情况下,最好使用生成器表达式:

def create_list_tuple(x):
  return tuple([] for _ in range(x))

lt = create_list_tuple(3)
print(lt)        #  =>  ([], [], [])
lt[0].append(1)  #  only modifies the first
print(lt)        #  =>  ([1], [], [])

答案 1 :(得分:1)

您可以尝试以下操作:

$('form[id="sbn"]').validate({
    rules: {
        businessName: {
            required: true
        }
    },
    highlight: function (element, errorClass) { // function will be called when there is an error on an element
        $("label[for='" + $(element).attr('name') + "']").addClass('text-danger').removeClass('text-success');
        console.log("Highlight: " + "label[for='" + $(element).attr('name') + "']");
        $(element).addClass('is-invalid').removeClass('is-valid');
    },
    unhighlight: function (element, errorClass) { // gets called when error is removed
        $("label[for='" + $(element).attr('name') + "']").removeClass('text-danger').addClass('text-success');
        console.log("Unhighlight: " + "label[for='" + $(element).attr('name') + "']");
        $(element).removeClass('is-invalid').addClass('is-valid');
    }
});

返回带有X的None的元组。

答案 2 :(得分:1)

我不确定@IBAction func ClickAction(_ sender: Any) { let actionSheetAlertController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) for title in self.titleData { let action = UIAlertAction(title: title.status, style: .default) { (action) in print("Title: \(title.id)") } let icon = UIImage.init(named: title.icon) action.setValue(icon, forKey: "image") action.setValue(CATextLayerAlignmentMode.left, forKey: "titleTextAlignment") actionSheetAlertController.addAction(action) } let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) actionSheetAlertController.addAction(cancelActionButton) self.present(actionSheetAlertController, animated: true, completion: nil) } 的合理值的“最快”方式是什么,但是一种方式是使用生成器:

n

或更自然地使用def create_none_tuple(n): return tuple(None for i in range(n))

itertools