如何在Python/MySQL中比较并合并两个列表?

2024-10-02 06:36:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想合并数据。下面是我的MySQL表。我想使用Python遍历两个列表的列表(一个是dupe='x',另一个是空dupe)。在

这是样本数据。实际数据非常庞大。在

例如:

a b c d e f key dupe
--------------------
1 d c f k l 1   x
2 g   h   j 1    
3 i   h u u 2
4 u r     t 2   x

从上面的示例表中,期望的输出是:

^{pr2}$

到目前为止我所拥有的:

import string, os, sys
import MySQLdb
from EncryptedFile import EncryptedFile

enc = EncryptedFile( os.getenv("HOME") + '/.py-encrypted-file')
user = enc.getValue("user")
pw = enc.getValue("pw")

db = MySQLdb.connect(host="127.0.0.1", user=user, passwd=pw,db=user)

cursor = db.cursor()
cursor2 = db.cursor()

cursor.execute("select * from delThisTable where dupe is null")
cursor2.execute("select * from delThisTable where dupe is not null")
result = cursor.fetchall()
result2 = cursor2.fetchall()

for each record
    for each field
        perform the comparison and perform the necessary updates

             ### How do I compare the record with same key value and update the original row null field value with the non-null value from the duplicate? Please fill this void...


cursor.close()
cursor2.close()
db.close()

谢谢各位!在


Tags: the数据fromimportclosedbvaluenull
1条回答
网友
1楼 · 发布于 2024-10-02 06:36:06

好吧,让我们玩得开心点。。。在

mysql> create table so (a int, b char, c char, d char, e char, f char, `key` int, dupe char);
Query OK, 0 rows affected (0.05 sec)

mysql> insert into so values (1, 'd', 'c', 'f', 'k', 'l', 1, 'x'), (2, 'g', null, 'h', null, 'j', 1, null), (3, 'i', null, 'h', 'u', 'u', 2, null), (4, 'u', 'r', null, null, 't', 2, 'x');
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from so order by a;
+   +   +   +   +   +   +   +   +
| a    | b    | c    | d    | e    | f    | key  | dupe |
+   +   +   +   +   +   +   +   +
|    1 | d    | c    | f    | k    | l    |    1 | x    |
|    2 | g    | NULL | h    | NULL | j    |    1 | NULL |
|    3 | i    | NULL | h    | u    | u    |    2 | NULL |
|    4 | u    | r    | NULL | NULL | t    |    2 | x    |
+   +   +   +   +   +   +   +   +
4 rows in set (0.00 sec)

^{pr2}$

相关问题 更多 >

    热门问题