Home  >  Q&A  >  body text

Python two lists added

There is a set of lists, a, b, c,..., and I want to continuously add this set of lists to the same list, for example:

`a = ['a']
b = ['b']
c = ['c']
addall = [['a'], ['b'], ['c']]`

I only thought of using a for loop to do this. Is there any more pythonic method?

習慣沉默習慣沉默2711 days ago673

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-05-18 11:00:37

    There is no need to pay too much attention to the form, just be concise and easy to understand

    a = ['a']
    b = ['b']
    c = ['c']
    tt=[]
    tt.append(a)
    tt.append(b)
    tt.append(c)
    print tt
    #输出[['a'], ['b'], ['c']]
    

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-18 11:00:37

    In [1]: a = ['a', 'b', 'c']                 
                                                
    In [2]: b = ['d', 'e', 'f']                 
                                                
    In [3]: import itertools                    
                                                
    In [4]: itertools.chain(a, b)               
    Out[4]: <itertools.chain at 0x30fcd90>      
                                                
    In [5]: list(itertools.chain(a, b))         
    Out[5]: ['a', 'b', 'c', 'd', 'e', 'f']      
                                                

    reply
    0
  • 怪我咯

    怪我咯2017-05-18 11:00:37

    python2,3

    In [6]: a=['a']
    
    In [7]: b=['b']
    
    In [8]: a.extend(b)
    
    In [9]: a
    Out[9]: ['a', 'b']
    

    python2,3, I think this is more natural!

    In [1]: a=['a']
    
    In [2]: b=['b']
    
    In [3]: a+b
    Out[3]: ['a', 'b']
    

    python3

    In [1]: a=['a']
    
    In [2]: b=['b']
    
    In [3]: [*a,*b]
    Out[3]: ['a', 'b']
    

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-18 11:00:37

    d = [i for i in (a,b,c)]

    reply
    0
  • Cancelreply