简体   繁体   中英

Python: Save a tuple in a list

From data saved in a DataFrame, I have to re-create the format below (ie list(tuple(tuples))), so it should have the same structure as:

coord = [((9, 9), (10, 6), (11, 3),(12, 6))]

So far I have been able to create the tuples from DataFrame by this code:

coord_y = tuple(data_df['data'].iloc[i:])
coord_x = tuple(data_df['data'].index.values[i:])

coord = list(zip(coord_x, coord_y)) # stack into (x,y) coord

which yields:

[(9, 9), (10, 6), (11, 3), (12, 6)]

Which is wrong because it is missing the "outer" tuple and should look like this:

[((9, 9), (10, 6), (11, 3),(12, 6))]

What am I doing wrong?

tuple() creates a tuple with all the data instead of a list() , and enclosing brackets [] create a new list with one element - early created tuple:

coord = [tuple(zip(coord_x, coord_y))] # stack into (x,y) coord

One of these should do:

[(tuple(zip(coord_x, coord_y), ))]

or

[(*zip(coord_x, coord_y), )]

Just wrap your zip in a tuple.

coord_y = tuple(data_df['data'].iloc[int(time_steps[-1]-l-1):])
coord_x = tuple(data_df['data'].index.values[int(time_steps[-1]-l-1):])

coord = [tuple(zip(coord_x, coord_y))] # stack into (x,y) coord

if your dataframe is df = pd.DataFrame({"data":[9,9,10,6,11,3,12,6]})

you could ise the itertools module:

from itertools import islice
import pandas as pd
def group_elements(lst, chunk_size):
    lst = iter(lst)
    return iter(lambda: tuple(islice(lst, chunk_size)), ())
df = pd.DataFrame({"data":[9,9,10,6,11,3,12,6]})
print([x for x in group_elements(df["data"],2)])

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