I have the following code in Python and I am an unsure about how the for loop here is working.
cur.execute("SELECT CUST_ID, COMPANY, LASTNAME, CITY, STATE FROM
mytable")
colnames = [desc[0] for desc in cur.description]
How does this for work ?
[desc[0] for desc in cur.description]
What is desc[0
]?
Based on the code you've given us it seems like desc
is an array itself and thus colnames
is an array of all the desc[0]
you get from each desc
in cur.description
desc[0]
is the first item in desc as arrays in Python are zero-indexed.
它使用可迭代对象,尤其是下一个方法,它将消耗对象内部的值,直到停止迭代为止,它的作用类似于生成器对象...。
When in doubt of something, try to recreate the thing. Althought, it could be anything iterable, we could assume it's just a list, then:
description = [['first'], ['second', 'third'], [x, y, z], [...], ...]
colnames = [desc[0] for desc in description]
in the output you'll have: ['first', 'second', x, ... ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.