数组保持空

2024-09-26 18:10:30 发布

您现在位置:Python中文网/ 问答频道 /正文

single_item_arrays = []
component_text_ids = []

def getText_identifiers(component_id) :
    if component_id is 'powersupply':
        for i in ['Formfactor','PSU',]:
            component_text_ids.append(i)
        single_item_arrays = formaten,PSU = [],[]

getText_identifiers('powersupply')
print(single_item_arrays)
print(component_text_ids)

结果是

[]
['Formfactor', 'PSU']

我希望如果出现这种情况,应该创建数组,以便将被刮取的数据放在两个不同的数组中。你知道吗

我尝试了一些方法,但仍然无法从函数内部的if语句创建数组


Tags: textididsif数组itempsucomponent
2条回答

一般不赞成,但如果在较新版本的Python上显式声明变量global,则可以从函数内部从技术上更改全局变量的赋值。全局变量通常被认为是bad thing,因此请谨慎使用-但您最好了解它作为语言的一个特性。你知道吗

single_item_arrays = []
component_text_ids = []

def getText_identifiers(component_id) :
    global single_item_arrays # Notice the explicit declaration as a global variable
    if component_id is 'powersupply':
        for i in ['Formfactor','PSU',]:
            component_text_ids.append(i)
        single_item_arrays = formaten,PSU = [],[]

getText_identifiers('powersupply')
print(single_item_arrays)
print(component_text_ids)

另见Use of "global" keyword in Python

我个人会使用以下方法,用显式返回变量替换全局变量:

def getText_identifiers(component_id) :
    single_item_arrays, component_text_ids = [], []
    if component_id is 'powersupply':
        for i in ['Formfactor','PSU',]:
            component_text_ids.append(i)
        single_item_arrays = formaten,PSU = [],[]
    return single_item_arrays, component_text_ids

single_item_arrays, component_text_ids = getText_identifiers('powersupply')
print(single_item_arrays)
print(component_text_ids)

您不能为全局变量(single_item_arrayscomponent_text_ids)赋值,但您可以进行像append这样的就地更改。你知道吗

相关问题 更多 >

    热门问题