📜  Python|拆分和传递列表作为单独的参数

📅  最后修改于: 2022-05-13 01:54:43.132000             🧑  作者: Mango

Python|拆分和传递列表作为单独的参数

随着编程范式的出现,需要修改一种编码方式。一种这样的范例是 OOPS。在这方面,我们有一种称为模块化的技术,它代表使不同的模块/功能在程序中执行独立的任务。在这种情况下,我们需要传递的不仅仅是变量,还有一个列表。让我们讨论可以执行此任务的某些方式。

方法 #1:使用tuple()
可以使用tuple()执行此任务。在此,我们将对列表转换为元组,并通过这种方式将各个元素分隔为变量,准备发送到函数。

# Python3 code to demonstrate working of
# Split and Pass list as separate parameter
# using tuple()
  
# Helper function for demonstration
def pass_args(arg1, arg2):
    print("The first argument is : " +  str(arg1))
    print("The second argument is : " +  str(arg2))
  
# initialize list
test_list = [4, 5]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Split and Pass list as separate parameter
# using tuple()
one, two = tuple(test_list)
pass_args(one, two)
输出 :
The original list is : [4, 5]
The first argument is : 4
The second argument is : 5

方法 #2:使用* operator
使用 *运算符是执行此任务的最推荐方法。 *运算符将对偶列表解包到 args 中,从而解决了我们的问题。

# Python3 code to demonstrate working of
# Split and Pass list as separate parameter
# using * operator
  
# Helper function for demonstration
def pass_args(arg1, arg2):
    print("The first argument is : " +  str(arg1))
    print("The second argument is : " +  str(arg2))
  
# initialize list
test_list = [4, 5]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Split and Pass list as separate parameter
# using * operator
pass_args(*test_list)
输出 :
The original list is : [4, 5]
The first argument is : 4
The second argument is : 5