代码之家  ›  专栏  ›  技术社区  ›  ThinkCode

pythonistas,如何在mysql中从上到下从左到右移动数据(每个id都有多个值)?

  •  2
  • ThinkCode  · 技术社区  · 15 年前

    手头的任务是将表1中的数据移动到表2中的数据。

    表(1)

    ID  Val
    --  ---
    1   a
    1   b
    1   c
    2   k
    3   l
    3   m 
    3   n
    

    VAL列取决于每个ID的唯一值数目。在这种情况下,它是3个,但在现实世界中可以是20个!

    表(2)

    ID  Val1 Val2 Val3  
    --  --   --   --
    1   a    b    c
    2   k
    3   l    m    n
    

    如何处理VAL列的较小值(在本例中为3):

    我创建一个临时表。

    create table test(ID int not null, b int auto_increment not null,primary key(ID,b), Val varchar(255));
    

    然后我将数据插入到测试中。

    我得到以下信息(我必须手动创建VAL列):

    ID  Val  b
    --  ---  --
    1   a    1
    1   b    2
    1   c    3
    2   k    1
    3   l    1
    3   m    2
    3   n    3
    

    我知道这是一个繁琐的过程,需要大量的手工工作。这是在我爱上巨蟒之前!对于这个问题,我们非常感谢在python中有一个有效的解决方案!

    这就是我到目前为止所拥有的

    import MySQLdb
    import itertools
    import dbstring
    
    cursor = db.cursor()
    
    cursor.execute("select ID, val from mytable")
    mydata = cursor.fetchall()
    
    IDlist = []
    vallist = []
    finallist = []
    
    for record in mydata:
        IDlist.append(record[1])
        vallist.append(record[2])
    
    zipped = zip(IDlist,vallist)
    zipped.sort(key=lambda x:x[0])
    
    for i, j in itertools.groupby(zipped, key=lambda x:x[0]):
        finallist = [k[1] for k in j]
    finallist.insert(0, i)
    finallist += [None] * (4 - len(finallist))  ### Making it a uniform size list
        myvalues.append(finallist)
    
    cursor.executemany("INSERT INTO temptable VALUES (%s, %s, %s, %s)", myvalues)
    
    
    db.close()
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   mouad    15 年前

    做这个的方法是使用 itertools.groupby

    import itertools
    
    a = [(1, 'a'), (1, 'b'), (2, 'c')]
    
    # groupby need sorted value so sorted in case
    a.sort(key=lambda x:x[0])
    
    for i, j in itertools.groupby(a, key=lambda x:x[0]):
        print i, [k[1] for k in j]
    

    返回

    1 ['a', 'b']
    2 ['c']