python - Issues ith loop is django -
i fetching info many users db , array in info collected having 2 rows each user , lastly column value different rest of values same like
r1 --> , b , c , d , 1 (user1) r2 -- > , b , c , d , 2 (user1) r3 --> z , x , v , n , 3 (user2) r4 -- > z , x , v , n , 4 (user2)
now want create array include 1 row corresponding each user consist of every value like
r1 --> , b , c , d , 1 , 2 (user1) r2 -- >z , x , v , n , 3 , 4 (user2)
i have tried loop , resulted array consist of lastly record , wanted array consist of records users.
e.g.
cursor.execute("some query ") numrows = int(cursor.rowcount)
let num rows returns value 4.
then
for in range(numrows):
pass
will loop 4 times , consist values 2 users.
but when returns resulted array consist value of lastly user only.
so please suggest me way when for in range(numrows):
array returns consist of records not lastly user record
edited:
i have tried while loop as
arr=[] while arr in row: arr= row[0][1]
but when homecoming arr , empty if homecoming row[0][1] shows value of column.
thanks in advance.
assuming info sorted first 4 entries (which can in sql), can transform info using next code:
from itertools import groupby operator import itemgetter rows=[ ('a' , 'b' , 'c' , 'd' , 1), ('a' , 'b' , 'c' , 'd' , 2), ('z' , 'x' , 'v' , 'n' , 3), ('z' , 'x' , 'v' , 'n' , 4)] out = [] key,group in groupby(rows, itemgetter(0,1,2,3)): new_row = list(key) v in group: new_row.append(v[4]) out.append(new_row) print out
which prints
[['a', 'b', 'c', 'd', 1, 2], ['z', 'x', 'v', 'n', 3, 4]]
here thought you: utilize first 4 entries keys in dictionary.
from collections import defaultdict rows=[ ('a' , 'b' , 'c' , 'd' , 1), ('a' , 'b' , 'c' , 'd' , 2), ('z' , 'x' , 'v' , 'n' , 3), ('z' , 'x' , 'v' , 'n' , 4)] d = defaultdict(list) r in rows: d[tuple(r[0:4])].append(r[4]) print d[('a' , 'b' , 'c' , 'd')] print d[('z' , 'x' , 'v' , 'n')]
prints
[1, 2] [3, 4]
with approach not matter if rows sorted first 4 columns
python django loops
No comments:
Post a Comment