gpt4 book ai didi

python - 函数不返回外部定义的变量

转载 作者:行者123 更新时间:2023-12-01 07:26:25 24 4
gpt4 key购买 nike

我有嵌套函数,用于对列表列表的索引进行分区,对应于相同的元素(列表)。

我的第一次尝试不是从内部函数返回我需要的列表。我认为这是因为输出列表仅在函数内部创建。所以我修改了脚本。我现在在外部定义我的输出列表,如组织集。它被传递给内部函数并由内部函数修改。然而,正确修改的列表并未从函数 ind_list_renew 传递到函数 find_like_tissues_set!

#!/usr/bin/env python

import numpy as np

l1 = [1,2,3]

l2=[2,3]

l3=[1,2,3]

l4=[2,3,4]

l5=[2,3]

mylist = [l1,l2,l3,l4,l5]
liketissuesets = []

def listidentity(v,b,f):
if len(v) != len(b):
return []
else:
for j in range(len(b)):
if v[j]!=b[j]:
return []
else:
return [f]


def ind_list_renew(changinglist, liketissuesets):
a=changinglist[0]
b=mylist[a]
common = []

for f,v in enumerate(mylist):
common = common + listidentity(v,b,f)

print(common)
liketissuesets = liketissuesets + [common]
print(liketissuesets)
changinglist = changinglist.tolist()
indtodelete = [j for j,k in enumerate(changinglist) if k in common]
changinglist = np.delete(changinglist, indtodelete)

if len(changinglist) != 0:
ind_list_renew(changinglist, liketissuesets)
else:
print('yay', liketissuesets)
return liketissuesets


def find_like_tissues_set(mylist, liketissuesets):

indoriginal = np.arange(len(mylist))
c=ind_list_renew(indoriginal, liketissuesets)
print(c)
return c

b=find_like_tissues_set(mylist, liketissuesets)

print(b)

最佳答案

真的,您不需要全局的liketissuesets。您可以像这样重构代码:

def ind_list_renew(changinglist, liketissuesets):
# stuff omitted

if len(changinglist) != 0:
return ind_list_renew(changinglist, liketissuesets)
else:
print('yay', liketissuesets)
return liketissuesets


def find_like_tissues_set(mylist):
indoriginal = np.arange(len(mylist))
c = ind_list_renew(indoriginal, [])
print(c)
return c

b = find_like_tissues_set(mylist)

print(b)

关于python - 函数不返回外部定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57427330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com