【问题标题】:Keep the list through functions通过函数保持列表
【发布时间】:2014-04-10 21:59:41
【问题描述】:

我用 Python 编写了这段代码:

   liste_usager = input("Veuillez entrer la liste d'entiers:")

liste = []
for n in liste_usager.split(' '):
       liste.append(int(n))



print(liste)
return liste
print('liste enregistrée')

print('que voulez-vous faire?')
boucle = True
while boucle:
    print('''
    1-afficher la liste
    2-trier la liste
    3-afficher la valeur maximale
    4-afficher la valeur minimale
    5-afficher la somme des valeurs
    6-inverser la liste
    7-modifier la liste
    0-retour
    ''')
    choix= input('choissisez une commande:')
    if choix =='1':
        print(liste_usager)
    if choix =='2':
        menu_tri()
    else:
        boucle= False

这只是返回一个整数列表,例如[1,2,3]。我的问题是我在同一个.py 文件中有其他def 函数/模块,这些模块需要使用这个gestionliste() 模块的结果列表。例如一个模块对列表进行排序,但是如何保持列出或将其转移到其他模块/功能而不再次询问用户?谢谢!

【问题讨论】:

  • 我认为你在上次编辑中杀死了一些东西。函数的def 在哪里?
  • 非常不清楚函数中有什么,没有什么。你能显示你的实际代码吗?最好把不需要的部分剪掉(比如打印语句)
  • 您在我的问题中看到的所有代码都是我的 def() 函数中我要求列表的内容。现在我需要“保存”结果列表以在其他模块中使用它(例如你可以在我的代码中看到的 menu_tri() 但实际上是另一个必须使用列表的 def() 函数。我不知道该怎么做。谢谢

标签: python list function module


【解决方案1】:

从函数返回列表,并将其传递给其他函数。

在函数底部添加

return liste

调用函数时,使用:

liste = gestionliste();

当你调用一个新函数时,像这样传入它:

otherFunction(liste)

当然你的其他函数必须把它作为参数。

def otherFunction(liste):
  # You can now use liste inside this function.

【讨论】:

  • 我编辑了我的问题,现在你看到了完整的代码;返回的问题是它刚刚结束循环并返回到我不想要的上一个菜单。我想保留列表在其他 def 模块中使用它的内存 -
【解决方案2】:

你有返回结果列表。

 def gestionliste():
    liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices

    liste = []
    for n in liste_usager.split(' '):
        liste.append(int(n))

    return liste

在您的原始代码副本中,您没有明确返回任何内容。所以默认情况下,它返回 None。

如果要在另一个函数中使用结果,比如 func2,你可以这样做:

temp = gestionliste()
func2(temp)

【讨论】:

  • 我编辑了我的问题,现在你看到了完整的代码;返回的问题是它刚刚结束循环并返回到我不想要的上一个菜单。我想保留列表在其他 def 模块中使用它的内存 -
【解决方案3】:

只需将您的 print 更改为 return

def gestionliste():
    liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices

    # I used list comprehension instead of your for loop
    liste = [int(n) for n in liste_usager.split(' ')]
    return liste

【讨论】:

  • 我编辑了我的问题,现在你看到了完整的代码;返回的问题是它刚刚结束循环并返回到我不想要的上一个菜单。我想保留列表内存在其他 def 模块中使用它
【解决方案4】:

从函数返回liste

例子:

# In function definiton file

def gestionliste():
    liste_usager = input("Veuillez entrer la liste d'entiers:") #user enter number(s) of his choices

    liste = []
    for n in liste_usager.split(' '):
           liste.append(int(n))
    return liste

# In your main script
liste = gestionliste()

【讨论】:

  • 我编辑了我的问题,现在你看到了完整的代码;返回的问题是它刚刚结束循环并返回到我不想要的上一个菜单。我想保留列表在其他 def 模块中使用它的内存 -
猜你喜欢
  • 1970-01-01
  • 2020-05-02
  • 2013-12-27
  • 2019-03-26
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
相关资源
最近更新 更多