I have a sqlite3 table where it contains 0 and 1. I would like to get the column names where the value is 1. I have tried both description and pragma method and for some reason the result is incorrect.
Following are my attempts:
.decription
allResults = c.execute("SELECT * FROM db_1.hope5 WHERE Vehicle = '{}'".format(veh))
all_columnNames = [tup[0] for tup in allResults.description]
inputs_columnNames = all_columnNames[9:]
inputcheck = [tup[9:] for tup in allResults.fetchall()]
inputSelected = [val for i, val in enumerate(inputs_columnNames) if inputcheck[0][i] == 1]
pragma
c = connection.cursor()
c.execute("PRAGMA TABLE_INFO(hope5)")
names = [tup[1] for tup in c.fetchall()]
names = names[2:]
result = c.execute("SELECT * FROM hope5 WHERE Vehicle = '{}' ".format(veh))
result = result.fetchall()
test = [names[index] for index, val in enumerate(result[0][2:]) if val==1]
Shape of the table
+----+-----+-----+-----+-----+-----+
| A | B | C | D | E | F |
+----+-----+-----+-----+-----+-----+
| 0 | 0 | 1 | 0 | 0 | 1 |
|----|-----|-----|-----|-----|-----|
| 1 | 0 | 0 | 0 | 1 | 0 |
+----+-----+-----+-----+-----+-----+
Based on my above code, the results need to be:
test = [A,C,E,F]
So the problem was:
inputSelected = [val for i, val in enumerate(inputs_columnNames) if inputcheck[0][i] == 1]
where the inputcheck[0] should have been j. by changing to the following it worked:
inputSelected_append = []
for j in range(len(inputcheck)):
inputSelected = [val for i, val in enumerate(inputs_columnNames) if inputcheck[j][i] == 1]
inputSelected_append.append(inputSelected)
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.