Hướng dẫn how do you extract a variable from a function in python? - làm cách nào để trích xuất một biến từ một hàm trong python?

Tôi có hàm Python tùy chỉnh sử dụng đầu vào của mô hình để tạo khung dữ liệu của giá trị y dự đoán, xác suất và một số tính năng khác. Tôi đang cố gắng trích xuất tên biến vật lý và sử dụng nó làm cột trong khung dữ liệu. Trong chức năng, biến "mô hình" biểu thị một mô hình được xác định. Có thể trích xuất chuỗi vật lý và sử dụng nó để tạo một cột mới?

Dưới đây là một ví dụ tái tạo cực kỳ cơ bản về mã của tôi

from sklearn.linear_model import LogisticRegression 
import pandas as pd```

df = {'odds_h': [150, 200, -300]}

log_reg = LogisticRegression()

def model_summary(model):
    
    df_summary = pd.DataFrame({'odds_h': df['odds_h'],
                               'model_type': model})
    
    return(df_summary)

model_summary(log_reg)

Đây là những gì đầu ra khung dữ liệu hiện đang hiển thị

Hướng dẫn how do you extract a variable from a function in python? - làm cách nào để trích xuất một biến từ một hàm trong python?

Đây là đầu ra dự định

Hướng dẫn how do you extract a variable from a function in python? - làm cách nào để trích xuất một biến từ một hàm trong python?

13 ví dụ mã Python được tìm thấy liên quan đến "các biến trích xuất". Bạn có thể bỏ phiếu cho những người bạn thích hoặc bỏ phiếu cho những người bạn không thích và đi đến dự án gốc hoặc tệp nguồn bằng cách theo các liên kết trên mỗi ví dụ. extract variables". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

ví dụ 1

def extract_source_variables(variables, varname, smvariables):
    '''Support function to extract the "atomic" variables used in a variable
    that is of instance `Subexpression`.
    '''
    identifiers = get_identifiers(variables[varname].expr)
    for vnm, var in iteritems(variables):
        if vnm in identifiers:
            if var in defaultclock.variables.values():
                raise NotImplementedError('Recording an expression that depends on '
                                          'the time t or the timestep dt is '
                                          'currently not supported in Brian2GeNN')
            elif isinstance(var, ArrayVariable):
                smvariables.append(vnm)
            elif isinstance(var, Subexpression):
                smvariables = extract_source_variables(variables, vnm,
                                                       smvariables)
    return smvariables 

Ví dụ 2

def extract_shared_variables(variables_1, variables_2):
  """Separates shared variables from the given collections.

  Args:
    variables_1: An iterable of Variables
    variables_2: An iterable of Variables

  Returns:
    A Tuple of ObjectIdentitySets described by the set operations

    ```
    (variables_1 - variables_2,
     variables_2 - variables_1,
     variables_1 & variables_2)
    ```
  """
  var_refs1 = object_identity.ObjectIdentitySet(variables_1)
  var_refs2 = object_identity.ObjectIdentitySet(variables_2)

  shared_vars = var_refs1.intersection(var_refs2)
  return (var_refs1.difference(shared_vars), var_refs2.difference(shared_vars),
          shared_vars) 

Ví dụ 3

def extract_variables(content: Any) -> Set:
    """ extract all variables in content recursively.
    """
    if isinstance(content, (list, set, tuple)):
        variables = set()
        for item in content:
            variables = variables | extract_variables(item)
        return variables

    elif isinstance(content, dict):
        variables = set()
        for key, value in content.items():
            variables = variables | extract_variables(value)
        return variables

    elif isinstance(content, str):
        return set(regex_findall_variables(content))

    return set() 

Ví dụ 4

def extract_files_containing_late_variables(start_files):
    found_files = []
    left_files = []

    for file_info in deepcopy(start_files):
        assert not any(_late_bind_placeholder_in(v) for k, v in file_info.items() if k != 'content'), (
            'File info must not contain late config placeholder in fields other than content: {}'.format(file_info)
        )

        if file_info['content'] and _late_bind_placeholder_in(file_info['content']):
            found_files.append(file_info)
        else:
            left_files.append(file_info)

    # All files still belong somewhere
    assert len(found_files) + len(left_files) == len(start_files)

    return found_files, left_files


# Validate all arguments passed in actually correspond to parameters to
# prevent human typo errors.
# This includes all possible sub scopes (Including config for things you don't use is fine). 

Ví dụ 5

def extract_variables(log_format):
    """
    Extract all variables from a log format string.
    :param log_format: format string to extract
    :return: iterator over all variables in given format string
    """
    if log_format == 'combined':
        log_format = LOG_FORMAT_COMBINED
    for match in re.findall(REGEX_LOG_FORMAT_VARIABLE, log_format):
        yield match 

Ví dụ 6

def extract_flake8_variables_names() -> Dict[str, str]:
    from flake8_variables_names import checker

    content = Path(checker.__file__).read_text()
    return get_messages(code='VNE', content=content) 

Ví dụ 7

def extract_variables(exp):
    if type(exp) == int:
        return set()

    if opcode(exp) in (
        "var",
        "mem",
        "cd",
        "storage",
        "call.data",
        "sha3",
        "calldatasize",
    ) or is_array(opcode(exp)):
        return set([exp])

    if type(exp) == str and exp in (
        "x",
        "y",
        "z",
        "sth",
        "unknown",
        "undefined",
        "callvalue",
        "number",
        "timestamp",
        "address",
    ):
        return set([exp])

    if type(exp) == str and exp != "data" and "data" in exp:
        return set([exp])

    if type(exp) != tuple:
        return set([exp])

    res = set()
    for e in exp[1:]:
        res = res.union(extract_variables(e))

    return res 

Ví dụ 8

def extract_variables_from_header(self, file_header):
        header_data = json.loads(file_header, object_pairs_hook=OrderedDict)
        flat_names = header_data[self.flat_names_tag]
        var_shapes = OrderedDict()
        for k, v in header_data[self.var_shape_tag].items():
            var_shapes[k] = tuple(v)
        var_dtypes = header_data[self.var_dtypes_tag]
        varnames = list(flat_names.keys())
        return flat_names, var_shapes, var_dtypes, varnames 

Ví dụ 9

def extract_variables(self) -> dict:
		variables = self.window.extract_variables()
		variables["package"] = core.current_package()
		project = variables.get('project_path')
		if project:
			variables['workspaceFolder'] = project
		return variables 

Ví dụ 10

def extract_source_variables(variables, varname, smvariables):
    '''Support function to extract the "atomic" variables used in a variable
    that is of instance `Subexpression`.
    '''
    identifiers = get_identifiers(variables[varname].expr)
    for vnm, var in iteritems(variables):
        if vnm in identifiers:
            if var in defaultclock.variables.values():
                raise NotImplementedError('Recording an expression that depends on '
                                          'the time t or the timestep dt is '
                                          'currently not supported in Brian2GeNN')
            elif isinstance(var, ArrayVariable):
                smvariables.append(vnm)
            elif isinstance(var, Subexpression):
                smvariables = extract_source_variables(variables, vnm,
                                                       smvariables)
    return smvariables 
0

Ví dụ 11

def extract_source_variables(variables, varname, smvariables):
    '''Support function to extract the "atomic" variables used in a variable
    that is of instance `Subexpression`.
    '''
    identifiers = get_identifiers(variables[varname].expr)
    for vnm, var in iteritems(variables):
        if vnm in identifiers:
            if var in defaultclock.variables.values():
                raise NotImplementedError('Recording an expression that depends on '
                                          'the time t or the timestep dt is '
                                          'currently not supported in Brian2GeNN')
            elif isinstance(var, ArrayVariable):
                smvariables.append(vnm)
            elif isinstance(var, Subexpression):
                smvariables = extract_source_variables(variables, vnm,
                                                       smvariables)
    return smvariables 
1

Ví dụ 12

def extract_source_variables(variables, varname, smvariables):
    '''Support function to extract the "atomic" variables used in a variable
    that is of instance `Subexpression`.
    '''
    identifiers = get_identifiers(variables[varname].expr)
    for vnm, var in iteritems(variables):
        if vnm in identifiers:
            if var in defaultclock.variables.values():
                raise NotImplementedError('Recording an expression that depends on '
                                          'the time t or the timestep dt is '
                                          'currently not supported in Brian2GeNN')
            elif isinstance(var, ArrayVariable):
                smvariables.append(vnm)
            elif isinstance(var, Subexpression):
                smvariables = extract_source_variables(variables, vnm,
                                                       smvariables)
    return smvariables 
2

Ví dụ 13

def extract_source_variables(variables, varname, smvariables):
    '''Support function to extract the "atomic" variables used in a variable
    that is of instance `Subexpression`.
    '''
    identifiers = get_identifiers(variables[varname].expr)
    for vnm, var in iteritems(variables):
        if vnm in identifiers:
            if var in defaultclock.variables.values():
                raise NotImplementedError('Recording an expression that depends on '
                                          'the time t or the timestep dt is '
                                          'currently not supported in Brian2GeNN')
            elif isinstance(var, ArrayVariable):
                smvariables.append(vnm)
            elif isinstance(var, Subexpression):
                smvariables = extract_source_variables(variables, vnm,
                                                       smvariables)
    return smvariables 
3

Làm thế nào để bạn truy cập một biến bên trong một hàm trong Python?

Các biến được xác định bên trong các phương thức chỉ có thể được truy cập trong phương thức đó chỉ bằng cách sử dụng tên biến. Ví dụ - var_name. Nếu bạn muốn sử dụng biến đó bên ngoài phương thức hoặc lớp, bạn phải khai báo biến đó là toàn cầu.using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global.

Làm thế nào để bạn sử dụng một biến từ một chức năng khác trong Python?

Làm thế nào để bạn sử dụng một biến từ một chức năng khác trong Python? Biến có thể được gán cho đối tượng hàm bên trong phần thân hàm. Vì vậy, biến chỉ tồn tại sau khi hàm được gọi. Khi hàm đã được gọi, biến sẽ được liên kết với đối tượng hàm.The variable can be assigned to the function object inside the function body. So the variable exists only after the function has been called. Once the function has been called, the variable will be associated with the function object.

Làm thế nào để bạn nhập một biến vào một hàm trong Python?

Tuyên bố nhập khẩu..
Nhập và sau đó sử dụng.để truy cập biến ..
từ nhập và sử dụng các biến ..
từ nhập * và sau đó sử dụng các biến trực tiếp ..

Làm thế nào để bạn có được một biến từ một chuỗi?

Chuỗi vào tên biến trong python bằng hàm vars ().Thay vì sử dụng hàm locals () và toàn cầu () để chuyển đổi một chuỗi thành một tên biến trong python, chúng ta cũng có thể sử dụng hàm vars ().Hàm Vars (), khi được thực thi trong phạm vi toàn cầu, hoạt động giống như hàm Globals ().Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.