在 Python 中解压列表

Unpack a list in Python

假设我有一个 MySQL table 我通过 MySQL 数据库访问。我有一个标准

SELECT statement:
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d'" % (1000)

然后我用光标执行它并如下所示提取列。

   cursor.execute(sql)
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]

是否可以在一条语句中分配所有列名?类似于:

for row in results:
    fname, lname, age, sex, income = unpack(row)

我总能做到:

fname, lname, age, sex, income = row[0], row[1], row[2], row[3], row[4]

但是我的 table 中有 30 多个专栏,这让我很痛苦。 请注意,虽然我现在正在使用 MySQL,但我希望它尽可能与数据库无关;我们仁慈的霸主可能会决定随时将所有内容移植到另一个数据库。

就这样:

fname, lname, age, sex, income = row

if len(row)==5 它应该有效,否则,如果你有 python 3 你可以使用 extended iterable unpacking

fname, lname, age, sex, income, *other = row

other 将是所有剩余元素的列表。

如果你有 python 2: 您可以使用 answer:

中的一个小函数
def unpack_list(a, b, c, d, e, *f):
    return a, b, c, d, e, f

fname, lname, age, sex, income, other = unpack_list(*row)

如果你只想要前 5 个元素,就像@Ev.Kounis 的意思,你可以这样做:

fname, lname, age, sex, income = row[:5]
results = [[1,2,3,4,5],
['a', 'b', 'c', 'd', 'e'],
[True, False, True, False, True]
]

for one, two, three, four, five in results:
    print one, two, three, four, five
>>> 1 2 3 4 5
>>> a b c d e
>>> True False True False True

您也可以在 for 循环本身中解压这些值。

完全不同的方法怎么样?

您可以使用 DictCursor 并按名称引用事物。例如,

cursor = db.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
    function_with_fname(row['fname'])
    function_with_age(row['age'])