简体   繁体   中英

python combine multiple sublist in to single list by group

How to combine these two sublist in to single sublist grouped by datetime? Because in the two sublist common factor is timestamp.I hope someone can help me on this.

   [[('2017-08-08 10:00:38', 5.0), ('2017-08-08 10:05:38', 8.0), ('2017-08-08 10:10:38', 7.5), ('2017-08-08 10:15:38', 8.3), ('2017-08-08 10:20:38', 5.0), ('2017-08-08 10:25:38', 5.0), ('2017-08-08 10:30:38', 5.0), ('2017-08-08 10:35:38', 5.0), ('2017-08-08 10:40:38', 55.0), ('2017-08-08 10:45:38', 85.0), ('2017-08-08 10:50:38', 55.0), ('2017-08-08 10:55:38', 5.0), ('2017-08-08 11:00:38', 53.0)], 
    [('2017-08-08 10:00:38', 11.2), ('2017-08-08 10:05:38', 10.0), ('2017-08-08 10:10:38', 13.0), ('2017-08-08 10:15:38', 101.0), ('2017-08-08 10:25:38', 10.0), ('2017-08-08 10:30:38', 10.0), ('2017-08-08 10:35:38', 110.0), ('2017-08-08 10:45:38', 100.5), ('2017-08-08 10:50:38', 100.5), ('2017-08-08 10:55:38', 10.05), ('2017-08-08 11:00:38', 10.10)]]

Desired Output: Example

a - Timestamp

[[a, x0,x1], [b, y0,y1], [c, z0,z1]] 

Update: Extremely sorry for changing the desired output format ,but this format will help me.Thanks

You could use the following, just set x = [your list].

i = 0
list = []
while i < len(x):
  for j in x[i]:
    list.append(j[0])
  i += 1

i = 0
while i < len(x):
  for j in x[i]:
    list.append(j[1])
  i += 1

final = tuple(list)

RESPONSE TO COMMENT:

i = 0
list = []
list2 = []
list3 = []
while i < len(x[0]):
  list.append(x[0][i][0])
  list2.append(x[0][i][1])
  i += 1

j = 0
while j < len(x[1]):
  list.append(x[1][j][0])
  list3.append(x[1][j][1])
  j += 1

final = [list, list2, list3]

Try this:

data = [
    [('2017-08-08 10:00:38', 5.0), ('2017-08-08 10:05:38', 8.0), ('2017-08-08 10:10:38', 7.5), ('2017-08-08 10:15:38', 8.3), ('2017-08-08 10:20:38', 5.0), ('2017-08-08 10:25:38', 5.0), ('2017-08-08 10:30:38', 5.0), ('2017-08-08 10:35:38', 5.0), ('2017-08-08 10:40:38', 55.0), ('2017-08-08 10:45:38', 85.0), ('2017-08-08 10:50:38', 55.0), ('2017-08-08 10:55:38', 5.0), ('2017-08-08 11:00:38', 53.0)],
    [('2017-08-08 10:00:38', 11.2), ('2017-08-08 10:05:38', 10.0), ('2017-08-08 10:10:38', 13.0), ('2017-08-08 10:15:38', 101.0), ('2017-08-08 10:25:38', 10.0), ('2017-08-08 10:30:38', 10.0), ('2017-08-08 10:35:38', 110.0), ('2017-08-08 10:45:38', 100.5), ('2017-08-08 10:50:38', 100.5), ('2017-08-08 10:55:38', 10.05), ('2017-08-08 11:00:38', 10.10)]
]

data_dicts = [dict(obj) for obj in data]
final_data = [
    [time_stamp]+[d.get(time_stamp) for d in data_dicts] for time_stamp in set().union(*data_dicts)
]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM