How to assign each element of a list to a separate variable?

前端 未结 7 1748
花落未央
花落未央 2020-12-01 14:12

if I have a list, say:

ll = [\'xx\',\'yy\',\'zz\']

and I want to assign each element of this list to a separate variable:

v         


        
7条回答
  •  余生分开走
    2020-12-01 14:43

    generally speaking it is not suggested to use that kind of programming for a large number of list elements / variables.

    However the following statement works fine and as expected

    a,b,c = [1,2,3]
    

    This is called "destructuring".

    it could save you some lines of code in some cases, e.g. I have a,b,c as integers and want their string values as sa,sb,sc:

    sa, sb,sc = [str(e) for e in [a,b,c]]
    

    or, even better

    sa, sb,sc = map(str, (a,b,c) )
    

提交回复
热议问题