简体   繁体   English

如何在python中将字符串列表作为函数参数传递?

[英]How to pass list of string as function argument in python?

I'm having a list of string and i need to pass it to function as a parameter.我有一个字符串列表,我需要将它作为参数传递给函数。

a_list = ['apple-banana','brinjal-carrot','cucumber']

function_call = fruit(a_list)

def fruit(a_list):
  print("Inside Function:")
  print(a_list)
  if(len(a_list)!=0):
     for i in a_list:
        print(i)

But what I'm getting for a_list is something like this:但是我得到的 a_list 是这样的:

['a','p','p','l','e','-','b','a','n','a','n','a',....]

What I need is:我需要的是:

Inside Function:
'apple-banana'
'brinjal-carrot'
'cucumber'

Where I'm going wrong.?我哪里错了。?

Thanks.谢谢。

Removing the redundant code with some highlights:删除多余的代码,并有一些亮点:

a_list = ['apple-banana','brinjal-carrot','cucumber']

def fruit(a_list):       # no need to check for the len or if the a_list exists, the for loop takes care of that
    for i in a_list:           
        print(i)
        
fruit(a_list) # your function is not returning anything so no point of assigning 

OUTPUT:输出:

apple-banana                                                                                                                                                                
brinjal-carrot                                                                                                                                                              
cucumber

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM