简体   繁体   中英

Convert tuple to list of elements

I'm coming from this question Get information out of sub-lists in main list elegantly , where a great solution was proposed (two actually).

The issue I have right now is that the answer given assumes a certain number of elements in a list (I never said the number of elements could change so it was my fault really) to generate the final list.

This is the MWE of the code:

a = [[0,1.1, 0.5, 99,99,0.7], [0,0.3, 1.4,99,99, 0.2], [1,0.6, 0.2,99,99, 1.], [1,1.1, 0.5,99,99, 0.3], [2,0.2, 1.1,99,99, 0.8], [2,1.1, 0.5,99,99, 1.], [3,1.2, 0.3,99,99, 0.6], [3,0.6, 0.4,99,99, 0.9], [4,0.6, 0.2,99,99, 0.5], [4,0.7, 0.2,99,99, 0.5]]

a_processed = []

from collections import defaultdict
nums = defaultdict(list)
for arr in a:
    key = tuple(arr[1:5]) # make the first two floats the key
    nums[key].append( arr[5] ) # append the third float for the given key

a_processed = [[k[0], k[1], k[2], k[3], round(sum(vals)/len(vals),2)] for k, vals in nums.items()]

which returns:

a_processed = [[0.7, 0.2, 99, 99, 0.5], [0.3, 1.4, 99, 99, 0.2], [0.6, 0.2, 99, 99, 0.75], [0.6, 0.4, 99, 99, 0.9], [1.2, 0.3, 99, 99, 0.6], [0.2, 1.1, 99, 99, 0.8], [1.1, 0.5, 99, 99, 0.67]]

I want to replace the last line which explicitly names the elements k[0], k[1], k[2], k[3] to something more general. I tried simply using:

a_processed = [[k, round(sum(vals)/len(vals),2)] for k, vals in nums.items()]

but that stores k as a tuple inside each sub-list:

a_processed = [[(0.7, 0.2, 99, 99), 0.5], [(0.3, 1.4, 99, 99), 0.2], [(0.6, 0.2, 99, 99), 0.75], [(0.6, 0.4, 99, 99), 0.9], [(1.2, 0.3, 99, 99), 0.6], [(0.2, 1.1, 99, 99), 0.8], [(1.1, 0.5, 99, 99), 0.67]]

So how can I generalize that line to any number of elements without having to explicitly write down each one?

Convert the tuple to a list using list(k) , then extend that list with whatever other elements you need it to contain.

(You can concatenate lists in python using the + operator.)

a_processed = [list(k) + [round(sum(vals)/len(vals),2)] for k, vals in nums.items()]

If I got your question right, the following is what you seek.

a_processed = [list(k)[:4] + [round(sum(vals)/len(vals),2)] for k, vals in nums.items()]

The + operator joins the 2 lists in given order.

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